Friday, February 13, 2009

Thread Synchronization

Synchronization:

  • The keyword synchronized can be apply only for methods and blocks. Ie., We can’t apply synchronized keyword for the classes and variables.
  • If a method (or block) declared as the synchronized at a time only one thread is allowed to execute that synchronized area on any given object.
Advantage: Prevent data corruption, achieve security.
Limitation: Because of synchronized keyword 2 threads are not allowed to execute concurrently on any object, hence the waiting time of the threads will increase, which results in low performance of the system.
A class can contain both synchronized and non synchronized methods.
  • If a thread calls synchronized method on any object, first this thread got the lock, it is allowed to any synchronized method on that object.
  • If a thread executing any synchronized method on the given object at that time no other thread is allowed to execute any synchronized method on that object.
  • If a thread executing any synchronized method the remaining threads are allowed simultaneously to execute nay non synchronized method on that object.
  • Every Object in java has a lock. At the time of synchronization only the lock concept will conme into the picture.
Synchronization example:-
class Display
{
public synchronized void show(String name)
{
for(int i=0;i<10;i++)
{
System.out.println(“Good Morning:”);
try
{
Thread.sleep(2000);
}
catch(InterruptedException e){}
System.out.println(name);
}
}
}
class MyThread extends Thread
{
Display d;
String name;
MyThread(Display d, String name)
{
this.d=d;
this.name=name;
}
public void run()
{
d.show(name);
}
}
class SynchronizedDemo
{
public static void main(String a[])
{
Display d=new Display();
MyThread t1=new MyThread(d,”java”);
MyThread t2=new MyThread(d,”Sun”);
t1.start();
t2.start();
}
}
output:
good morning : java ......10 times after good morning: sun ......10 times
If we are not putting synchronized keyword we will get some irregular output like
goodmorning :good morning:java good morning:sun..........like that

Class Level lock:
• If you want to execute any static synchronized method, first the thread should required a class level lock.
• If a thread has class level lock, it is allowed to execute any stock synchronized method. During that time no other thread is allowed to execute any static synchronized method. But the remaining threads are allowed to execute any static non synchronized methods of the same class.

0 comments:

Post a Comment