Implementing Concurrent Stack Using AtomicReference

Tags

, , , ,

When two or more threads are accessing shared object or shared collection which are not thread safe we usually end up with synchronizing the code. The synchronization helps to make it thread safe but has performance drawbacks. Hence we have set of concurrent collections available in java.util.concurrent which are thread safe and does not required (external)synchronization, which makes them extremely fast as compared to their synchronized counterpart.

But how it can be made thread safe without synchronizing. Well answer lies in synchronization itself. Why do we synchronize? Primarily for making a set of statements atomic to ensure thread safety. Well if that atomic nature can be achieved without the synchronization, we don’t need synchronization.

To get a more clear picture, lets take a example of stack. In a stack with have two main operations push() and pop(). The push() adds an item in front/head of the stack and pop remove the item from the front/head. So if we maintain front into some reference, every time a push or pop happens we need to update the front/head. Since there may multiple threads might be accessing the Stack simultaneously we need to update the front/head atomically. Every thread checks the front/head of the stack and sets new value based on value checked. If it finds the value of front/head is changed, this means that some other thread has called push() or pop() on the thread, otherwise it changes the front/head with new value based on operation(push() and pop()) called.

Here comes the AtomicReference which allows to compare and set the references atomically. This means we can create a simple thread safe stack without synchronization.

The following example shows a simple implementation of Concurrent Stack using AtomicReference. The ConcurrentStack<E> class has a private inner class StackNode<E> which is used to represent each node of the  stack, which is liked together by StackNode<E> next reference which of type AtomicReference.  The ConcurrentStack class maintains is head into head item as of type AtomicReference which is used to push() and pop() elements from it. In this implementation for push() and pop() , I have used a greedy approach where the thread will retry to push() or pop() until it succeeds. But its left up to the use case where it is required to be greedy or time out or fail if not able to push() or pop() in first try.

package com.mylib.concurrent;

public interface Stack <E>{

	public void push(E e);
	public E pop();

}
package com.mylib.concurrent;

import java.util.concurrent.atomic.AtomicReference;

public class ConcurrentStack<E> implements Stack {

	private AtomicReference<StackNode> head;
	/**
	 * Creates a unbounded concurrent queue
	 */
	public ConcurrentStack() {
		head = new AtomicReference();
	}

	/**
	 * This method will try to push item into stack until it succeeds
	 */
	@Override
	public void push(E e) {
		//Create a new item
		StackNode<E> newHead = new StackNode<E>(e);
		StackNode<E> headNode = null;
		do
		{
			headNode = head.get();
			newHead.next = headNode;
		}while(!head.compareAndSet(headNode, newHead));
	}

	/**
	 * This method will try to pop item from stack until it succeeds
	 */
	@Override
	public E pop() {
		StackNode<E> headNode = head.get();
		do
		{
			headNode = head.get();
			if(headNode == null)
				return null;
		}while(!head.compareAndSet(headNode, headNode.next));
		return headNode.item;
	}

	/**
	 * Inner class to hold stack items 
	 * @param <E>
	 */
	private class StackNode<E>{
		private E item;
		StackNode<E> next;

		public StackNode(E item) {
			this.item = item;
		}
	}

}

In above code a thread calls push() method, checks head of the stack and try to set with new head based on the value it had just checked. If the head remains same, it changes  head to new item and make new items next to head. Hence new item is pushed. If the value of head is changed since it has checked, this means some other thread has pushed or popped item from it. Hence the thread repeat the same steps checking head and retrying to set until it succeeds.

Same logic is applied to pop() where a thread trying to pop item from the thread checks head and try to set the head with head.next if value is head is not changed. If the value of head is changed this means some other thread has pushed or popped item from the stack, hence the thread  has to repeat the same process until it succeeds.

Note : This is sample code, just to understand how AtomicReference can be used to create concurrent data structure. A few corner case might not have covered.

Preventing Deadlock using Lock Ordering

Tags

, , ,

In one of my previous blog I have shared a example how a deadlock can happen due to threads contending for locks occupied by other threads. In this blog I am going to discuss what can be done to prevent the such scenarios.

If the worker threads needs to acquire two or more locks to finish their execution, the chances of deadlocks is very high. The solution to prevent deadlock in such scenario is very simple and that is Lock Ordering.

Lets take a simple example of two shared objects which are used by worker threads to finish their job say A and B. If we don’t have lock ordering, and two worker Thread 1 and Thread 2 trying to acquired lock A and lock B. Thread 1 takes lock on A, and Thread 2 takes lock on B. Now Thread 1 is trying to acquire lock B which is locked by Thread 2 and Thread 2 is trying to lock A which is acquired by Thread 1. Oh..we have a deadlock.

Now if some how we enforce that “lock A” needs to be acquired before “lock B”, we can solve the problem. So every thread that needs lock A and lock B, will try to get lock A first and then will try lock B. And hence the condition where one thread has lock B and trying to get lock A will not occur, since it has to get lock A first.

Now the question is if we have a set of shared object, how can we determine the lock ordering or in which order the locks need to be acquired ?

Well we can have a custom ordering declared if we want some, but then the problem is maintaining such ordering table or list if difficult in specially enterprise application. Also the changes of someone breaking the ordering very high more due to human mistakes etc.

The best way I can suggest to solve this problem is using the identityHashCode from Java System class.

System.identityHashCode(Object x)

This method returns the hashCode of the object as would be returned by default hashCode method(say when we hadn’t overridden the hashCode method in our object).

This utility from System class can be used to order the locks. Following a sample example:

if(System.identityHashCode(lockA) < System.identityHashCode(lockB))
{
	//acquire lock A
	synchronized (lockA)
	{
		//acquire lock B
		synchronized (lockB) 
		{
			//do work
		}
		
	}
}
else
{
	//acquire lock B
	synchronized (lockB) 
	{
		//acquire lock A
		synchronized (lockA) 
		{
			//do work
		}
	}
}

Note : This is a simple example with two locks, the same can be scaled for more than 2 locks.

Find all Permutations of a String

Tags

,

To find the all permutations of a string we can use dynamic programming. In order to do that lets try to find permutation for 1,2 and 3 character string and find out if we can find any pattern that can be applied on ‘n’ characters.

Permutation('a') : a

For two character string ‘ab’

Permutation('ab') : ab,ba

For three character string ‘abc’

Permutation('abc') : abc,acb,bac,bca,cab,cba

In above examples if we try to find pattern, the Permutation(‘a’) and Permutation(‘ab’) is constant. But Permutation(‘abc’) can be formed using Permutation(‘ab’) and ‘c’. i.e., we apply c at every possible place in 

Permutation('ab') = {ab,ba}

Hence we can find 

cab,acb,abc
cba,bca,bac

Hence final result

Permuatation('abc') : [cab,acb,abc,cba,bca,bac]

Hence same can applied for n character string where char[n] can be placed into Permutation of (n-1) characters.

Following is a simple and quick implementation in Java

package com.premute;

import java.util.HashSet;
import java.util.Set;

public class StringPermuter {

	public static void main(String[] args) {

		StringPermuter permuter = new StringPermuter();
		String[] perms = permuter.permute("abc");
		if(perms != null)
		{
			System.out.println("Total Permutaions : "+perms.length);
				if(perms.length >0)
				{
					for(String s:perms)
					System.out.println(s);
				}
		}
		
	}
	
	
	public String[] permute(String string)
	{
		if(string!= null)
		{
			char[] chars= string.toCharArray();
			if(chars.length == 0)
				return null;
			else if(chars.length == 1)
			{
				//Permutation for one char
                                String[] strs = new String[1];
				strs[0] = new StringBuilder().append(chars[0]).toString();
				return strs;
			}
			else if (chars.length == 2)
			{
				//Permutation for two chars
				String[] strings = new String[2];
				strings[0] = new StringBuilder().append(chars[0]).append(chars[1]).toString();
				strings[1] = new StringBuilder().append(chars[1]).append(chars[0]).toString();
				return strings;
			}
			else
			{
				Set set = new HashSet();
				//Find permuation of n-1 chars
				String[] permutations = permute(string.substring(0, chars.length-1));
				//nth char
				char ch = chars[chars.length-1];
				//Place nth char in all places in Permutation(n-1)
				for(String str : permutations)
				{
					char[] chrs = str.toCharArray();
					int x=0,y=0;
					StringBuilder newString = null;
					while(x<=chrs.length)
					{
						newString = new StringBuilder();
						y=0;
						while(y<x)
						{
							newString.append(chrs[y]);
							y++;
						}
						newString.append(ch);
						while(y<chars.length-1)
						{
							newString.append(chrs[y]);
							y++;
						}
						set.add(newString.toString());
						x++;
					}
				}
				
				return set.toArray(new String[0]);
			}
		}
		return null;
	}

}

Output for
String[] perms = permuter.permute(“a”);

Total Permutaions : 1
a

String[] perms = permuter.permute(“ab”);

Total Permutaions : 2
ab
ba

String[] perms = permuter.permute(“abc”);

Total Permutaions : 6
cab
abc
cba
bac
bca
acb

Note : This code has potential for improvements.

Find parentheses permutations

Tags

, ,

Finding all valid permutations of given set  of parentheses can be solved with dynamic programming. The way we solve it using dynamic programming is we solve it for 1,2 and 3 set of parentheses and so on until we find a patter which can be applied for n number of parentheses.

Lets look at the combination for n=1
()
For n=2
()() (())
For n=3
((())), ()(()), ()()(), (()()), (())()

So is it possible to produce the n=2 using combination from n=1. Yes, it can be i.e., for every combination of n=1 we try to add () before and after and one around it. So we produce

()() ,()() and (())

Since first two are same hence, the final result is

()(),(()))

Now lets see we can apply same for n=3 using combination from n=2.
Apply one set before and after each of n=2

()()(),()()(),()(()),(())()

And one around each n=2

(()()),((()))

So final result after combining and removing duplicates

()()(),()(()),(())(),(()()),((()))

And hence same can be applied to n=1,2….k

Let see a sample code in Java to implement this:

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Parenthesis {

	public static void main(String[] args) {

		Parenthesis parenthis = new Parenthesis();
		Set sets = parenthis.getAllParenthesisCombination(3);
		System.out.println(sets);

	}

	public Set getAllParenthesisCombination(int n)
	{
		if(n==0)
			return null;
		else if(n==1)
		{
			Set set = new HashSet();
			set.add("()");
			return set;
		}
		else
		{
			Set set = getAllParenthesisCombination(n-1);
			Set newSet = new HashSet();
			for(String str:set)
			{
				newSet.add("()"+str);
				newSet.add(str+"()");
				newSet.add("("+str+")");
			}
			return newSet;
		}
	}

}

Output for n=1

[()]

Output for n=2

[()(), (())]

Output for n=3

[((())), ()(()), ()()(), (()()), (())()]

Output for n=4

[()()(()), (()()()), ((()))(), ()((())), ()(()()), ()(())(), ()()()(), (()())(), ((())()), (((()))), (())()(), (()(())), ((()()))]

Implementing partial search using Trie in Java

Tags

, , ,

The partial search or auto complete is usually implemented by data structure called Trie or more improved version of Trie such as Prefix Trie or Compressed Trie. I am going to create a simple example to show how we can implement Partial search using Trie in Java.

In this case the Trie is created before search is done. The root node of the Trie contains the alphabets which are starting alphabets of the each word in our word list. Word list is the list of all words upon which we are going to search. And each node has n child where n is number of possible next characters.

So to create a Trie we will add all words in the Trie and then start searching for the words from it using prefix.

If we have words such as :
JavaOne
JavaTwo
JavaThree
JavaFour
JavaFive

The Trie would look like

       ()
       |
       J
       |
       a
       |
       V
       |
       a
    /  |   \ 
   F   O    T
  /\   |    /\
 i  o  n   h  w
 |  |  |   |  |
 V  u  e   r  o
 |  |      |
 e  r      e
           |
           e

To start with Lets Create a TrieNode Class:

package com.search;

import java.util.LinkedList;
import java.util.List;

public class TrieNode {
	
	
	public TrieNode(char charecter) {
		this.character = charecter;
		this.childs = new LinkedList();
	}
	private char character;
	private List childs;
	public char getCharacter() {
		return character;
	}
	public void setCharacter(char character) {
		this.character = character;
	}
	public List getChilds() {
		return childs;
	}
	public void setChilds(List childs) {
		this.childs = childs;
	}
	
}

Now lets create the Trie Class

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class Trie {

	private TrieNode root;

	/**
	 *  Add the give word into the Trie
	 * @param word
	 */
	public void addWord(String word)
	{
		if(root == null)
		{
			root = new TrieNode(' ');
		}
		TrieNode start = root;
		char[] charecters = word.toCharArray();
		for(char c : charecters)
		{
			if( start.getChilds().size() == 0)
			{
				TrieNode newNode = new TrieNode(c);
				start.getChilds().add(newNode);
				start = newNode;
			}
			else
			{
				ListIterator iterator = start.getChilds().listIterator();
				TrieNode node=null;
				while(iterator.hasNext())
				{
					node = iterator.next();
					if(node.getCharacter() >= c)
						break;
				}
				if(node.getCharacter() == c)
				{
					start = node;
				}
				else
				{
					TrieNode newNode = new TrieNode(c);
					iterator.add(newNode);	
					start = newNode;
					
				}
			}
		}
		
	}
	
	/**
	 *  This method takes and prefix string and returns all possible string that can be formed from the given prefix
	 * @param prefix
	 * @return
	 */
	public List search(String prefix)
	{
		if(prefix == null || prefix.isEmpty())
			return null;
		
		char[] chars = prefix.toCharArray();
		TrieNode start = root;
		boolean flag = false;
		for(char c : chars)
		{
			if(start.getChilds().size() > 0)
			{
				for(TrieNode node : start.getChilds())
				{
					if(node.getCharacter() == c)
					{
						start = node;
						flag=true;
						break;
					}
				}
			}
			else
			{
				flag = false;
				break;
			}
		}
		if(flag)
		{
			List matches = getAllWords(start,prefix);
			return matches;
		}
		
		return null;
	}
	
	/**
	 *  This method returns list string that can be formed from the given node
	 * @param start : Node from to start
	 * @param prefix : String prefix that was formed till start node
	 * @return
	 */
	private List getAllWords(TrieNode start,final String prefix)
	{
		if(start.getChilds().size() == 0)
		{
			List list = new LinkedList();
			list.add(prefix);
			return list;
		}
		else
		{
			List list = new LinkedList();
			for(TrieNode n: start.getChilds())
			{
				list.addAll(getAllWords(n, prefix+n.getCharacter()));
			}
			return list;
		}
		
	}
	
}

And finally lets create the  test class to test it:

import java.util.List;

public class SearchTest {

	public static void main(String[] args) {
		
		Trie trie = new Trie();
		trie.addWord("Java");
		trie.addWord("JavaOne");
		trie.addWord("JavaTwo");
		trie.addWord("JavaThree");
		trie.addWord("JavaFour");
		trie.addWord("JavaFive");
		
		
		List matches = trie.search("Java");
		if(matches==null || matches.size() == 0)
		{
			System.out.println("No match found");
		}
		else
		{
			for(String str:matches)
			{
				System.out.println(str);
			}
		}

	}

}

Output of the the above test

JavaOne
JavaFive
JavaFour
JavaTwo
JavaThree

If we search for

List<String> matches = trie.search("JavaT");

We get the results as

JavaTwo
JavaThree

Using NavigableSet to search in collection

Tags

, ,

To search an element from the collections in Java we do contains() check. Which returns false if no such elements exists. But in case we do want to know if there is any element exist which is either equals, higher or lower than the element, we can use the NavigableSet. NavigableSet provide following methods to do such checks:

E lower(E e) : Returns greatest element in the set which is less the given element e.
E floor(E e) : Return the greatest element in set which is less than or equal to given element e. It return e if it is present in collection .
E higher(E e) : Return the lowest element in the set which is greater than given element e.
E ceiling(E e) : Returns the lowest element in set which is greater than or equals to the given it. It return e, if it is present in collection

The generic implementation for this interface is TreeSet and concurrent one is ConcurrentSkipListSet

To get a more clear picture of these method lets take a example:

import java.util.NavigableSet;
import java.util.TreeSet;

public class SkipListTest {

public static void main(String[] args) {

NavigableSet<String> set = new TreeSet<>();

set.add("Java");
set.add("Java One");
set.add("Java Two");
set.add("Java Three");
set.add("Java Four");
set.add("Java Five");

String searchString = "Java One";
System.out.println("Floor of "+searchString+" : "+set.floor(searchString));
System.out.println("Lower of "+searchString+" : "+set.lower(searchString));
System.out.println("Ceiling of"+searchString+" : "+set.ceiling(searchString));
System.out.println("Higher of "+searchString+" : "+set.higher(searchString));

}

}

Lets run and see the output of the code:

Floor of Java One : Java One
Lower of Java One : Java Four
Ceiling ofJava One : Java One
Higher of Java One : Java Three

Now if we remove the item ‘Java One’ from the set  and run again

import java.util.NavigableSet;
import java.util.TreeSet;

public class SkipListTest {

public static void main(String[] args) {

NavigableSet<String> set = new TreeSet<>();

set.add("Java");
// set.add("Java One");
set.add("Java Two");
set.add("Java Three");
set.add("Java Four");
set.add("Java Five");
String searchString = "Java One";
System.out.println("Floor of "+searchString+" : "+set.floor(searchString));
System.out.println("Lower of "+searchString+" : "+set.lower(searchString));
System.out.println("Ceiling of"+searchString+" : "+set.ceiling(searchString));
System.out.println("Higher of "+searchString+" : "+set.higher(searchString));

}

}

Output

Floor of Java One : Java Four
Lower of Java One : Java Four
Ceiling of Java One : Java Three
Higher of Java One : Java Three

As we see here since the item is not present in the collection the floor() and lower() both returns the same object. Same applies to heigher() and ceiling() methods.

Java Stored Procedure in Oracle Database

Tags

, ,

Oracle database comes with its own Java Virtual Machine and since it has JVM we can run our Java Classes in the DB Server itself. Why would some one need to run java on DB server ? The best answer would be to have stored procedure in Java which can use JDBC to do some operation on database.

For more details on this subject please refer to http://docs.oracle.com/cd/B28359_01/java.111/b31225/cheight.htm

In this blog I am taking to very very simple example to show how can we create a Java Stored Procedure and Run them.

So we start with a simple Java class ‘HelloWorld’ and also have a method which is public static [Required to make public static]

public class HelloWorld{        
public static void sayHello()
{
System.out.println("Hello World");
}
}
We are going to treat this method as our stored procedure. This is where we would like to put our jdbc code to manipulate DB as shown in the example  http://docs.oracle.com/cd/B28359_01/java.111/b31225/cheight.htm
So now we have the Java Class ready to uploaded in Oracle Database. In $ORACLE_HOME/bin there loadjava tool, using which we can upload our java class into DB server.
[me@myhost]$ ./loadjava -u sys@myhost:1521:orcl-v -r -t HelloWorld.java
Password:
********
arguments: '-u' 'me@myhost:1521:orcl' '-v' '-r' '-t' 'HelloWorld.java'
creating : source HelloWorld
loading  : source HelloWorld
resolving: source HelloWorld
Classes Loaded: 0
Resources Loaded: 0
Sources Loaded: 1
Published Interfaces: 0
Classes generated: 0
Classes skipped: 0
Synonyms Created: 0
Errors: 0
Now lets create package def and package body for our Java Stored Procedure so that it can be called as normal PL/SQL.
create or replace
PACKAGE hello as
PROCEDURE sayHello;
END hello;
PACKAGE HELLO compiled
create or replace
PACKAGE BODY hello AS
PROCEDURE sayHello as LANGUAGE JAVA
NAME 'HelloWorld.sayHello()';
end hello;
PACKAGE BODY HELLO compiled
And its time to call our store procedure and test.
SQL> SET SERVEROUTPUT ON;
SQL> CALL dbms_java.set_output(2000);
Call completed.
SQL> CALL hello.sayHello();
Hello World
Call completed.

Joining Threads | A Simple Example

Tags

, , ,

The join() method in Thread Class allows one thread to wait for completion of another thread. For example:

t.join();

The above code will take the current thread in execution and join behind the thread referred by ‘t’. That means the current thread executing the code t.join() will not resume execution until thread ‘t’ completes.

Lets take a simple coding example to understand it better. Lets say we have three threads ONE, TWO and THREE and we want them to run in sequence i.e., THREE runs after TWO and TWO runs after ONE. So obviously we are going to join them one after another..but HOW?

Lets see HOW.

Our first Class is MyThread class which is our thread class.

package mishra.bagish;

public class MyThread implements Runnable {

	private Thread thread;
	public MyThread(Thread t)
	{
		thread = t;
	}

	@Override
	public void run() {

		System.out.println(Thread.currentThread().getName()+" Going to join given thread");
		if(thread!=null)
		{
			try{
					thread.join();
			}
			catch(InterruptedException e)
			{
				e.printStackTrace();
			}
		}
		System.out.println(Thread.currentThread().getName()+" START");
		//do some code
		System.out.println(Thread.currentThread().getName()+" END");
	}

}

So in above class, we are having a reference to a thread for which the current thread is going to wait for. Actually when thread.start() run by jvm the run() method of the thread might get the cpu time any time and there is no fixed schedule. So what we have done is after printing first line we are calling join() to the join the current thread behind the thread referenced by ‘thread’. Once the thread ‘thread’ completes, the only the current comes backs to runnable state.

Now lets see a main code which has main() method and creates all threads and starts them.

package mishra.bagish;

public class MainCasss {
	public static void main(String[] args) {
		Thread one = new Thread(new MyThread(null),"ONE");
		Thread two = new Thread(new MyThread(one),"TWO");
		Thread three = new Thread(new MyThread(two),"THREE");
		one.start();
		two.start();
		three.start();
	}
}

So here we are starting three threads ONE, TWO and THREE. Each of them is passed with a reference of the thread which they are going to join or follow. Thread ONE is not given any reference since we want this thread to go first and rest to follow it.  So in this example TWO will join with ONE and THREE will join with two.

Output

TWO Going to join given thread
ONE Going to join given thread
THREE Going to join given thread
ONE START
ONE END
TWO START
TWO END
THREE START
THREE END

Although TWO got scheduled first followed by ONE followed by THREE. Since we joined TWO with ONE so TWO suspends it execution till ONE completes. And THREE suspends its execution till TWO completes. No matter how may times we runs this code, the thread starting sequence might change but the sequence of

ONE START
ONE END
TWO START
TWO END
THREE START
THREE END

will never change.

Explicit Vs Intrinsic Locks in Java | Ensuring Thread Scheduling fairness

Tags

, , ,

In java we have two types of locks available

1. Intrinsic Lock

2. Explicit Lock

Whenever we synchronize any object we get an Intrinsic Lock on that object. There is one more way to implement locking/synchronizing i.e. using Explicit Locks. From Java 1.5 java.util.concurrent.locks package provides some explicit locking classes which can be used to replace the the intrinsic locks. One of commonly used example of explicit lock is ReentrantLock.

There is a fair difference between throughput of Reentrant Lock over Intrinsic Lock in Java 1.5. That means the throughput of application using intrinsic lock goes down drastically as compared  to Reentrant Lock in case of increasing no of threads. This gap was fixed in 1.6 and now both behave quite same in even in multiple thread scenario.

This was a brief description about intrinsic and explicit locks in Java. Now there is question is when to use explicit and when to use intrinsic. There are many reasons to use explicit reasons. One of them is tryLock() method which helps to prevent the deadlock scenarion. I ll we discussing this in later blogs. But for now I am going to use a example to show ‘How can we ensure the thread scheduling fairness between threads using Explicit Locks‘.

So out problem is that in case of multiple threads asking for a shared lock, we want to ensure that the thread get the lock the longest thread in waiting on the lock object.

We will start with using intrinsic lock and see how it behaves, in case of multiple threads. In this example we have a Simple Monitor Class which we will using for Locking and it will be shared among threads.

Class : Monitor

package com.intrinsiclock;

public class Monitor {

}

As we see here it just a blank class, which we will be using to share between threads as a common lock object.

The other class in this example is out thread class:

Class : MyThread

package com.intrinsiclock;

public class MyThread implements Runnable {

private Monitor monitor;

public MyThread(Monitor monitor) {
super();
this.monitor = monitor;
}

@Override
public void run() {

printMessage("Entered run method...trying to lock monitor object");
synchronized (monitor) {
printMessage("Locked monitor object");
try{
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
printMessage("Releasing lock");
monitor.notifyAll();
}
printMessage("End of run method");

}

private void printMessage(String msg){
System.out.println(Thread.currentThread().getName()+" : "+msg);
}

}

This class has implemented run method, and get shared lock in its constructor. It tries to lock monitor using synchronise block on monitor. Once it is able to lock it sleeps for some time just to ensure other threads tries to lock this monitor. Once it wakes up it just release lock by notifying all other waiting threads. We have added simple print messages to show where the threads are and what they are doing.

And finally our main class which will invoke multiple threads contending for the locks:

Class: IntrinsicTest

package com.intrinsiclock;

public class IntrinsicTest {

public static void main(String[] args) {
System.out.println("=========Intrinsic Lock Test=======");
String[] myThreads = {"Therad ONE","Thread TWO","Thread THREE","Thread FOUR"};
Monitor monitor = new Monitor();
for(String threadName:myThreads)
{
new Thread(new MyThread(monitor),threadName).start();
}

}

}

One we run this example we get following output:

=========Intrinsic Lock Test=======
Therad ONE : Entered run method...trying to lock monitor object
Therad ONE : Locked monitor object
Thread THREE : Entered run method...trying to lock monitor object
Thread TWO : Entered run method...trying to lock monitor object
Thread FOUR : Entered run method...trying to lock monitor object
Therad ONE : Releasing lock
Therad ONE : End of run method
Thread FOUR : Locked monitor object
Thread FOUR : Releasing lock
Thread FOUR : End of run method
Thread TWO : Locked monitor object
Thread TWO : Releasing lock
Thread TWO : End of run method
Thread THREE : Locked monitor object
Thread THREE : Releasing lock
Thread THREE : End of run method

The output of this program will be different each time we run this code. Let me explain you the reason. As we here the Thread ONE has acquired the lock in the first place and meanwhile the Thread TWO,THREE and FOUR also came in and requested for lock. The order in which they came are THREE, TWO and FOUR. But when we see the output of the code, it is FOUR who got lock first followed by TWO and THREE. So basically FOUR jumped out of line and grabbed the lock once it was released by ONE.

The reason is notifyAll(). Actually the methods notify() and notifyAll() does not guarantee which one of the waiting thread will get lock. That is the reason we will get random sequence in which the threads gets lock in this example.

This is not what we wanted to achieve, but we wanted the thread who requested for lock first should get the lock first. But it is not possible in case of using intrinsic locks. So here comes the Explicit Locks for our help. The ReentrantLock has a special flag called fairness. By making ‘fair=true‘ it ensures that the lock in granted to the thread who requested first. By default ReentrantLock fair flag is false i.e. same behavior as intrinsic lock. But by just passing one argument to the constructor to the ReentrantLock class we can achieve the fairness we are looking for.

Lock lock = new ReentrantLock(true);

Lets take a example to show this. So our first class in our thread class

Class : MyThread

package com.explicitlock;

import java.util.concurrent.locks.Lock;

public class MyThread implements Runnable {

private Lock lock;

public MyThread(Lock lock) {
super();
this.lock = lock;
}

@Override
public void run() {

printMessage("Entered run method...trying to lock monitor object");
lock.lock();
try{
printMessage("Locked monitor object");
try{
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
finally{
printMessage("Realising lock");
lock.unlock();
}
printMessage("End of run method");

}

private void printMessage(String msg){
System.out.println(Thread.currentThread().getName()+" : "+msg);
}

}

As we can see here we are using Lock object to achieve synchronization in this thread class. The lock.lock() method is a blocking method. It blocks the current thread untill it gets the lock. Once it gets the lock it does same stuff as our previous example, sleeps for some time and release lock. Interestingly we are calling unlock() in finally block, this is very important to ensure that lock is release even the thread exist due to some abnormal termination. Otherwise its very difficult to detect such leaks when a thread died with un-released lock.

Now lets see the main class which invokes multiple thread with one shared lock, which all of them tries to lock:

Class : ExplicitLockTest

package com.explicitlock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ExplicitLockTest {

public static void main(String[] args) {
System.out.println("=========Explicit Lock Test=======");
String[] myThreads = {"Therad ONE","Thread TWO","Thread THREE","Thread FOUR"};
Lock lock = new ReentrantLock(true);
for(String threadName:myThreads)
{
new Thread(new MyThread(lock),threadName).start();
}

}

}

Here we have created a Lock object of ReentrantLock and shared among all threads. The catch is passing fair flag while creating the lock object:

Lock lock = new ReentrantLock(true);

Now lets run the code

=========Explicit Lock Test=======
Therad ONE : Entered run method...trying to lock monitor object
Therad ONE : Locked monitor object
Thread TWO : Entered run method...trying to lock monitor object
Thread THREE : Entered run method...trying to lock monitor object
Thread FOUR : Entered run method...trying to lock monitor object
Therad ONE : Realising lock
Therad ONE : End of run method
Thread TWO : Locked monitor object
Thread TWO : Realising lock
Thread TWO : End of run method
Thread THREE : Locked monitor object
Thread THREE : Realising lock
Thread THREE : End of run method
Thread FOUR : Locked monitor object
Thread FOUR : Realising lock
Thread FOUR : End of run method

Here we can see Thread ONE has acquired the lock first meanwhile the Thread TWO, THREE and FOUR also came in and requested for the lock. So once the lock got released by ONE it was allocated to TWO followed by THREE and FOUR. And this lock ensures that the thread who requested lock first get the lock first whenever available.

The catch is

Lock lock = new ReentrantLock(true);

If we don’t pass the the fair flag here, then it behaves same as intrinsic locks. But using fair flag achieves the fairness in thread lock allocation.

Note: Using fair flag results into drop of throughput of the application. Hence we should not be using anyway but whenever the the fairness is required.

Serializing Static Members of the Class

Tags

, ,

Serialization is nothing but storing the state of the object. So we can serialize an object instance to a file or any stream. But can we serialize static members ? If yes then how? Since static members are tied to class not instance, so this can confuse that can be really serialize those static values? My answer is yes why not. The static values are tied to Class level but every class is itself a instance of java.lang.Class hence the static values are also part of instances of Class type. And hence we can serialize them. Now the tricky part is how? Here is a example :

We have a Class called  StaticClass which has only one value as static.

package com.serialize;

public class StaticClass {
    public static int x=20;
}

We kept the value as public just for example. Now lets see how can we serialize this value. As I mentioned to serialize static value we need to have a instance of type java.lang.class and the serialize it. So our code for serialize is

package com.serialize;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SerializeStaticClass {

public static void main(String[] args) {
try{
  Class cls = Class.forName("com.serialize.StaticClass");
  File file = new File("MyClass.obj");
  FileOutputStream fileInputStream = new FileOutputStream(file);
  ObjectOutputStream objectInputStream = new ObjectOutputStream(fileInputStream);
  System.out.println("Serializing Class");
  objectInputStream.writeObject(cls);
  System.out.println("Serializing Class Complete");

}
catch (FileNotFoundException e) {
  e.printStackTrace();
}
catch (IOException e) {
  e.printStackTrace();
}
catch(ClassNotFoundException e)
{
  e.printStackTrace();
}
}
}

Now its time to write code to de-serialize and get the value back. Since we have used instance of Class type for serialization we will get the same Class type back while de-serialization . We will use reflection to retrieve the value from the instance of Class type.

package com.serialize;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializeStaticClass {

public static void main(String[] args) {
  FileInputStream fileInputStream = null;
  ObjectInputStream objectInputStream =null;
  File file = new File("MyClass.obj");
  try{
    fileInputStream = new FileInputStream(file);
    objectInputStream = new ObjectInputStream(fileInputStream);
    System.out.println("Reading object");
    Class cls = (Class)objectInputStream.readObject();
    int y=0;
    System.out.println("Value of x after deserialization is : "+cls.getField("x").getInt(y));
}
catch(IllegalAccessException e)
{
  e.printStackTrace();
}
catch(NoSuchFieldException e)
{
  e.printStackTrace();
}
catch (FileNotFoundException e) {
  e.printStackTrace();
}
catch (IOException e) {
  e.printStackTrace();
}
catch (ClassNotFoundException e) {
  e.printStackTrace();
}
}

}

Now lets Run the Serialize class followed by the de-serialize class.

OUTPUT of SerializeStaticClass

Serializing Class
Serializing Class Complete

OUTPUT of DeserializeStaticClass

Reading object
Value of x after deserialization is : 20

So we got value of back from de-serializing the object of Class type. The serialize and de-serialize in this example can two tweaked further to achieve the desired purpose.