Category Archives: Java

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);
    }
}

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();
        }
    }
}

1863. Sum of All Subset XOR Totals

key idea is how to generate all subset of array.

take 3 elements of arrays for example,

[a, _, _] -> [1, 0, 0]
[_, b, _] -> [0, 1, 0]
[a, b, _] -> [1, 1, 0]
[_, _, c] -> [0, 0, 1]
[a, _, c] -> [1, 0, 1]
[_, b, c] -> [0, 1, 1]
[a, b, c] -> [1, 1, 1]

integer i is loop through 1 to Math.pow(2, nums.length) – 1, for each integer, we check how many 1 bit

i & 1, if it is 1, we get nums[index] out as elements for subarray.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 
class Solution {
    public int subsetXORSum(int[] nums) {
        int result = 0;
    	int x = (int)Math.pow(2, nums.length) - 1;
        for(int i=1;i<=x;i++) {
        	int p = i;
        	int r = 0;
        	for(int j=0;j<nums.length;j++) {
        		int t = p & 1;
        		p >>= 1;
 
        		if (t == 1) {
    				r ^= nums[j];
        		}
        	}
 
        	result += r;
        }
 
        return result;
    }
}

java – Spring Mergeable

There are 4 type of Mergeable Object in Spring

ManagedList
ManagedProperties
ManagedMap
ManagedSet

Take ManagedList as example

if mergeEnabled is set to be false, merge will stop
if parent is null, return itself.
and finally it will add parent firstly and then add children.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
	@Override
	@SuppressWarnings("unchecked")
	public List<E> merge(@Nullable Object parent)
	{
		if (!this.mergeEnabled) {
			throw new IllegalStateException("Not allowed to merge when the 'mergeEnabled' property is set to 'false'");
		}
		if (parent == null) {
			return this;
		}
		if (!(parent instanceof List)) {
			throw new IllegalArgumentException("Cannot merge with object of type [" + parent.getClass() + "]");
		}
		List<E> merged = new ManagedList<>();
		merged.addAll((List<E>) parent);
		merged.addAll(this);
		return merged;
	}

java – method bridge

java reflection could get all methods of a class.

isBridge() could check whether method is bridged or not.

when we override parent class general type method in child class, method will become bridged.

here is example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package org.spring.main;
 
import java.lang.reflect.Method;
 
import org.springframework.core.BridgeMethodResolver;
 
public class BridgeMethodResolverEntry {
 
	public class Node<T> {
 
	    public T data;
 
	    public Node(T data) { this.data = data; }
 
	    public void setData(T data) {
	        System.out.println("Node.setData");
	        this.data = data;
	    }
	}
 
	public class MyNode extends Node<Integer> {
 
	    public MyNode(Integer data) { super(data); }
 
	    @Override
	    public void setData(Integer data) {
	        System.out.println("MyNode.setData");
	        super.setData(data);
	    }
	}
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		BridgeMethodResolverEntry x = new BridgeMethodResolverEntry();
		MyNode resolver = x.new MyNode(5);
		Method[] declaredMethods = resolver.getClass().getDeclaredMethods();
 
		for (int i = 0; i < declaredMethods.length; i++) {
		            Method declaredMethod = declaredMethods[i];
		            String methodName = declaredMethod.getName();
		            Class<?> returnType = declaredMethod.getReturnType();
		            Class<?> declaringClass = declaredMethod.getDeclaringClass();
		            boolean bridge = declaredMethod.isBridge();
		            System.out.print((i+1) + " method name is" + methodName + ", return type is " + returnType + "  ");
		            System.out.print(bridge ? " is Bridge Method" : " is not Bridge Method");
		            System.out.println("  it is declared at "+declaringClass.getSimpleName()+"");            
		}                        
 
	}
 
}

Java – Static Initialization Block

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.dw.lib.test;
 
public class StaticInitializationBlock {
 
	static  
    {  
        System.out.println("STATIC BLOCK");  
    } 
 
	public StaticInitializationBlock() {
		System.out.println("constructor");
	}
 
	public static void main(String[] args) {
 
		StaticInitializationBlock block = new StaticInitializationBlock();
 
		System.out.println("MAIN METHOD");
 
	}
 
}

output:
STATIC BLOCK
constructor
MAIN METHOD

log4j src – parse log4j.xml building DocumentBuilder

log4j uses DocumentBuilder to parse log4j.xml

here is example code which is same as log4j original source code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
 
package main;
 
import java.io.*;
import java.net.*;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
 
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
 
public class DocumentBuilderEntry {
 
	public static void loop(Node node) {
	    // do something with the current node instead of System.out
	    System.out.println(node.getNodeName());
 
	    NodeList nodeList = node.getChildNodes();
	    for (int i = 0; i < nodeList.getLength(); i++) {
	        Node currentNode = nodeList.item(i);
	        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
	            //calls this method for all the children which is Element
	        	loop(currentNode);
	        }
	    }
	}
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		URL url = DocumentBuilderEntry.class.getResource("log4j.xml");
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
		try {
			DocumentBuilder parser = factory.newDocumentBuilder();
			URLConnection uConn = url.openConnection();
 
			uConn.setUseCaches(false);
			InputStream stream = uConn.getInputStream();
			try {
			  InputSource src = new InputSource(stream);
			  src.setSystemId(url.toString());
			  Document doc = parser.parse(src);
			  loop(doc.getDocumentElement());
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
			  stream.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
 
 
 
	}
 
}

Spring – MultiValueMap and LinkedMultiValueMap

MultiValueMap is common object type in Spring Utils source code.

Here is an example of how to use it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
MultiValueMap<String, String> multiValueMaps = new LinkedMultiValueMap<String, String>();
multiValueMaps.add("Tom", "Book");
multiValueMaps.add("Tom", "Pen");
 
multiValueMaps.add("ABC", "Company");
multiValueMaps.add("ABC", "WebSite");
 
for(String key: multiValueMaps.keySet()) {
	List<String> value = multiValueMaps.get(key);
	System.out.print(key + "\t");
	for(String s: value) {
		System.out.print(s + "\t");
	}
	System.out.println();
}

Java – Runtime.getRuntime().addShutdownHook()

a useful method when program done and run last step task.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 
 
public class AddShutdownHookTest {
 
	static class Message extends Thread {
 
		public void run() {
			System.out.println("Bye.");
		}
	}
 
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
 
			// register Message as shutdown hook
			Runtime.getRuntime().addShutdownHook(new Message());
 
			// print the state of the program
			System.out.println("Program is starting...");
 
			// cause thread to sleep for 3 seconds
			System.out.println("Waiting for 3 seconds...");
			Thread.sleep(3000);
 
			// print that the program is closing
			System.out.println("Program is closing...");
 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}