Sunday, 2 December 2012

Synchronization in Java

Posted by Naveen Katiyar On 11:31 1 comment
Synchronization is a process of executing the multiple threads in mutually exclusive manner(completing whole task at once).Synchronization is achieved by using the concept of monitors(lock).

By default ,threads are executed in asynchronous manner.It means,if multiple threads are  sharing the common resource,these threads may access the common resource  at the same time.But sometimes ,we need the synchronous execution of threads,i.e. mutual exclusion.There are so many situations in which we need proper synchronization in the execution of threads,such as implementation of stack,consumer producer problem,implementation of shared account.

In java ,a lock can be acquired in the following two ways:-
i)Implicit lock
ii)Explicit lock

Implicit lock: In java,every object has an implicit lock that can be used by any thread to lock the resources.

Ques-How Thread acquires the lock?
A lock can be acquired by a thread in the following two ways:-

a)If thread is executing the synchronized non-static method,the lock is obtained from current Object.
b)If thread is executing synchronized block,the lock is acquired by the thread from the specific Object.

A method could be made synchronized by placing 'synchronized' keyword before method definition.

Note:-If a thread is executing static synchronized method of a class,the lock is acquired from the current class.Like the object Lock,all the java classes also have the class specific lock and class specific lock is acquired by a thread,if thread is executing static synchronized statements.

Synchronized blocks:-Sometimes we need to execute only specific set of statements of a method in synchronized manner.But if a method is synchronized,its all statements are executed in synchronized manner.
        synchronized blocks are used to execute only specific set of statements in synchronized manner.

syntax:       synchronized(object lock/class lock)
                {
                }


Below is given the Stack implementation:-

                                         Stack.java
This is shared resource which needs to be accessed by two threads in synchronized manner.


package mypack;
public class Stack {

static int elements[] = new int[5];
static int top = -1;
String s1 = "abc";

public void push(int i)
{
//sychronized(s1) lock from  string object
synchronized(String.class)//lock from class
{
System.out.println(i+" is going to be pushed..");
if(top>=4)
{
System.out.println("stack is overflow...");
}
else
{
top++;
elements[top] = i;
System.out.println(i+" is pushed.");
}
}
}


public void pop()
{
//sychronized(s1) lock from  string object
synchronized(String.class)//lock from class
{

if(top<0)
{
System.out.println("stack is underflow...");
}
else
{
System.out.println(elements[top]+" is going to be popped.");
System.out.println(elements[top]+" is  popped.");
top--;
}
}
}
}

Now we are going to make two threads,one thread for pushing data on stack and another one for popping.


                                             PushThread.java
package mypack;

public class PushThread extends Thread {
Stack st=null;
public PushThread(Stack st)
{
this.st=st;
}

public void run()
{
for(int i=0;i<10;i++)
st.push(i+5);
}


}




                                             PopThread.java

package mypack;

public class PopThread extends Thread {
Stack st=null;
public PopThread(Stack st)
{
this.st=st;
}

public void run()
{
for(int i=0;i<10;i++)
st.pop();
}


}

Finally we are going to write StackTest class which will use both the threads to perform push and pop operations in synchronized manner.


                                                    StackTest.java

package mypack;


public class StackTest {

public static void main(String arg[])
{
System.out.println("main thread started..");
System.out.println("push and pop thread are going to be created by main thread..");
Stack st = new Stack();
PushThread push= new PushThread(st);
PopThread pop= new PopThread(st);
System.out.println("starting push and pop thread..");
push.start();
pop.start();
try
{
push.join();
pop.join();
}catch(Exception e){e.printStackTrace();}
System.out.println("main thread is completed..");
}

}

NOTE:Implicit lock is acquired by thread when it executes synchronized context.

Explicit Lock:-Explicit lock is represented by an object of java.util.Concurrent.locks.ReentrantLock;
An object of this class represents an explicit lock that can be acquired by a thread by invoking its lock() method and a thread release the lock by invoking its unlock() method.

Advantage of explicit lock-Consider a method in which we want some statements to be executed in synchronized manner, some other in unsynchronized manner and again some in synchronized manner.Before jdk 1.5,we could have achieved this using two synchronized blocks.But now,it could be easily achieved using  
explicit lock.

Note:This facility was added from jdk 1.5.

Above given concept could be explained using following example-

package mypack;

import java.util.concurrent.locks.ReentrantLock;

public class Morning {
ReentrantLock l = new ReentrantLock();
public void goodMorning()
{
for(int i=0;i<5;i++)
{
try
{
l.lock();
System.out.println("good");
System.out.println("morning");
}catch(Exception e){
e.printStackTrace();
}
finally
{
l.unlock();
}
}
}

}

Now we write a thread which will execute goodMorning() of shared resource class.


package mypack;

public class Child extends Thread {

Morning m;
Child(Morning m)
{
this.m=m;
}
  public void run()
  {
m.goodMorning();
  }
}

The following class will make the two thread which will use the shared resource.

package mypack;

public class ReentrantTest {
public static void main(String arg[])
{
Morning m = new Morning();
Child ch1=new Child(m);
Child ch2=new Child(m);
ch1.start();
ch2.start();
}

}





1 comments:

Anonymous said...

There are actually several companies that you can broaden the scope of your customer base.
This dish _________ too spicy. As Google and many partnership s have
preached for years, it's not as easy to game the system in their favor. Now on web Partnership play major role in any Partnership technique. He or she will use the pictures that you and Oscar created during that conversation and then convert the mental images to conversion copy.

my webpage :: web optimization services