Java ParallelStream


import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class ParallelStreamTest {
    public static void main(String[] args) {
        List<BigInteger> integers = new ArrayList<>();
// fill data
        integers.add(new BigInteger("134123124325234234"));
        integers.add(new BigInteger("1341231243252"));
        integers.add(new BigInteger("134123124325234234"));
        integers.add(new BigInteger("134123124325234234"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));

        BigInteger result = integers.parallelStream()
                .reduce(BigInteger.ONE, (a, e) -> a.multiply(e));
        System.out.println(result);

    }
}

synchronized locks

synchronized locks all methods in one object
These are both methods of the same object, and both are marked as synchronized. If even one method is being executed, all other synchronized methods of the same object become inaccessible to other threads

public class Main {
    public static void main(String [] args) {
        SharedClass sharedObject = new SharedClass();
 
        Thread thread1 = new Thread(() -> {
            while (true) {
                sharedObject.increment();
            }
        });
 
        Thread thread2 = new Thread(() -> {
            while (true) {
                sharedObject.decrement();
            }
        });
 
        thread1.start();
        thread2.start();
    }
 
    static class SharedClass {
        private int counter = 0;
 
        public synchronized void increment() {
            this.counter++;
        }
 
        public synchronized void decrement() {
            this.counter--;
        }
    }
}

synchronized lock different object
thread could execute both critical sections at same time.

public class Main {
    public static void main(String [] args) {
        SharedClass sharedObject = new SharedClass();
 
        Thread thread1 = new Thread(() -> {
            while (true) {
                sharedObject.incrementCounter1();
            }
        });
 
        Thread thread2 = new Thread(() -> {
            while (true) {
                sharedObject.incrementCounter2();
            }
        });
 
        thread1.start();
        thread2.start();
    }
 
    static class SharedClass {
        private int counter1 = 0;
        private int counter2 = 0;
 
        private Object lock1 = new Object();
        private Object lock2 = new Object();
 
        public void incrementCounter1() {
            synchronized (lock1) {
                this.counter1++;
            }
        }
 
        public void incrementCounter2() {
            synchronized (lock2) {
                this.counter2++;
            }
        }
    }
}

Babel Cli to translate html loop in jsx to React.createElement

step 1: create a project using following command line

npm init
npm install --save-dev babel-cli
npm install babel-plugin-transform-react-jsx

save following code into build.sh

./node_modules/.bin/babel --plugins transform-react-jsx index.jsx

step 2: create .babelrc

{
    "presets": ["es2015", "react"]
}

step 3: create index.jsx

import React from 'react';

const items = [
  { id: 1, name: 'Item 1' },
  { id: 2, name: 'Item 2' },
  { id: 3, name: 'Item 3' },
];

function MyComponent() {
  return (
    <div>
      <h1>Items List</h1>
      <ul>
        {items.map(item => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default MyComponent;

final step: run build.sh

'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var items = [{ id: 1, name: 'Item 1' }, { id: 2, name: 'Item 2' }, { id: 3, name: 'Item 3' }];

function MyComponent() {
  return _react2.default.createElement(
    'div',
    null,
    _react2.default.createElement(
      'h1',
      null,
      'Items List'
    ),
    _react2.default.createElement(
      'ul',
      null,
      items.map(function (item) {
        return _react2.default.createElement(
          'li',
          { key: item.id },
          item.name
        );
      })
    )
  );
}

exports.default = MyComponent;

Summary

you could see that items.map(item => ()) has been translated into _react2.default.createElement(…items.map(function (item) {}… ).

Emacs – Use Etags to investigate Linux Kernel source code

Build TAGS file

Navigate Linux kernel source code folder to generate TAGS file.

find . -name “*.[chCH]” -print | etags –

Set Default TAGS file

Tags-table-list contains list of directories that contain TAGS file, All of Dir should contain TAGS file. Otherwise, search will stop at directory without TAGS file and print error message.

(setq tags-table-list '("~/.emacs.d" "/path/to/linux/kernel/src"))

Find Tag and Jump back

M-x find-tag         — jump to define

M-x xref-pop-mark-stack    — pop mark stack to jump back.

Linux Kernel may have different definition for one variable because of multiple Hardware architecture, we could jump all definition for one variable to find out right hardware architecture to view.

Java Stream – ParallelStream

Multiple All BigInteger in Array using Parallel Stream and reduce

package com.dw.thread;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

public class ParallelStreamTest {
    public static void main(String[] args) {
        List<BigInteger> integers = new ArrayList<>();
// fill data
        integers.add(new BigInteger("134123124325234234"));
        integers.add(new BigInteger("1341231243252"));
        integers.add(new BigInteger("134123124325234234"));
        integers.add(new BigInteger("134123124325234234"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));
        integers.add(new BigInteger("134123124"));

        BigInteger result = integers.parallelStream()
                .reduce(BigInteger.ONE, (a, e) -> a.multiply(e));
        System.out.println(result);

    }
}

Java Thread – Calculate result = ( base1 ^ power1 ) + (base2 ^ power2)

Idea is to use two java threads, one thread calculates base1 ^ power1 using BigInteger and another thread calculates base2 ^ power2. Use thread.join() to wait for both thread to complete and sum result from both thread.

package com.dw.thread;

import java.math.BigInteger;

public class ComplexCalculation {

    public BigInteger calculateResult(BigInteger base1, BigInteger power1, BigInteger base2, BigInteger power2) throws InterruptedException {
        BigInteger result;
        /*
            Calculate result = ( base1 ^ power1 ) + (base2 ^ power2).
            Where each calculation in (..) is calculated on a different thread
        */

        PowerCalculatingThread thread1 = new PowerCalculatingThread(base1, power1);
        PowerCalculatingThread thread2 = new PowerCalculatingThread(base2, power2);

        thread1.start();
        thread2.start();

        thread1.join();   // important: wait thread to complete
        thread2.join();  
        result = thread1.getResult().add(thread2.getResult()); // add two result

        return result;
    }

    private static class PowerCalculatingThread extends Thread {
        private BigInteger result = BigInteger.ONE;
        private BigInteger base;
        private BigInteger power;

        public PowerCalculatingThread(BigInteger base, BigInteger power) {
            this.base = base;
            this.power = power;
        }

        @Override
        public void run() {
           /*
           Implement the calculation of result = base ^ power
           */
            for (BigInteger i = BigInteger.ZERO; i.compareTo(power) != 0; i = i.add(BigInteger.ONE)) {
                result = result.multiply(base);
            }
        }

        public BigInteger getResult() { return result; }
    }
    public static void main(String[] args) throws InterruptedException {
        ComplexCalculation c = new ComplexCalculation();
        BigInteger result = c.calculateResult(new BigInteger("123"), new BigInteger("10"), new BigInteger("456"), new BigInteger("20"));

        System.out.println(result);
    }
}

Java Stream – Map and FlatMap

Here is an example from book, it converts list of string into list of chars without duplicated. it is good example to show what different between map and flatmap. basically map will keep original structure of input element while flatmap won’t keep structure of input element.

Mockito – ByteBuddy Examples

ByteBuddy is key framework used in Mockito, it will auto generated subclass and override default methods. Following code will print out “Hello ByteBuddy!”.

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.matcher.ElementMatchers;

public class ByteBuddyEntry {
    public static void main(String[] args)
    {
        DynamicType.Unloaded unloadedType = new ByteBuddy()
                .subclass(Object.class)
                .method(ElementMatchers.isToString())
                .intercept(FixedValue.value("Hello ByteBuddy!"))
                .make();

        Class<?> dynamicType = unloadedType.load(ByteBuddyEntry.class
                        .getClassLoader())
                .getLoaded();

        try {
            System.out.println(dynamicType.newInstance().toString());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

MySQL Core Src – Lex/Parse SQL Statement

SQL lex files:

sql/sql_lex.h、sql/lex_token.h、sql/lex.h、sql/lex_symbol.h

sql/gen_lex_token.cc、sql/sql_lex.cc

SQL grammar parser file:

sql/sql_yacc.yy、sql/sql_yacc.cc、sql/sql_yacc.h

SQL hint grammar parser file:

sql/sql_hints.yy、sql/sql_hints.yy.cc

mysql use bison (lex/yacc) to token sql statement and parse it, take sql_yacc.yy for example, it is main file contains all parse sql rules.