Wednesday, May 26, 2010

Difference between Synchronized method and Synchronized block

Why we need synchronization in multithreading?

Because multithreading introduces asynchronous behavior to your programs, there must be a way to enforce synchronicity when you need it. For example, when you want two threads to communicate and share a complicated data structure, you need some way to ensure that they never conflict with each other.

One way to synchronize object methods is using synchronized methods as shown below

synchronized void call(String message)
{
System.out.println(message);
}

But, it'll not work in all cases. For example, if you want to synchronize access to objects of a class that was not designed for multithreading or what if the class was not created by you, but by some third party and you don't have access to the code? Solution is that you simply put calls to the methods defined by this class inside a synchronized block as shown below

Synchronized(Object)
{
statements to be synchronized
}

Here Object is a reference to the object being synchronized. Synchronized block ensures that a call to a method that is member of this object occurs only after the current thread has successfully entered object's monitor. (Monitor is an exclusive lock for the object being synchronized)

No comments:

Post a Comment