Home           J2EE Concepts           JMS           Java Language           Contact           Back           Next           Bookmark this Page          










Some useful tips related to:
 - health & fitness
 - vehicle care
 - cooking
 - misc household tasks

Thread Synchronization


What is Synchronization - Synchronization means if multiple threads are trying to access same object, then ensuring that two or more threads don't update the object simultaneously.

Why Synchronization - Consider this example: two threads A & B are accessing same object X; A updates X & almost at the same time B also updates X. Later, thread A tries to read X; in this case X would be having values updated by thread B; hence the data received by thread A would become inconsistent. By synchronizing, we would ensure that no thread writes data while other one is accessing it (reading, updating, deleting etc.)

For this purpose, Java uses MONITOR. Once a thread enters a monitor, all other threads must wait until that thread exits the monitor.

In Java,each object has its own implicit monitor that is automatically entered when one of the object’s synchronized methods is called.

This also means, once a thread is executing a synchronized method, no other thread can call any other synchronized method on the same object.


How to use Synchronization?


Make use of synchronized keyword. You can use synchronized for synchronizing methods, as well as some specific line(s) of code.

It's syntax is:

synchronized(object) {
// statements to be synchronized
}

In this case, object is referring to the object on which you want to put restriction of being used simultaneously by multiple threads.
Let us consider following scenario: Suppose class of this object A was not written for multithreaded access, and hence it does not have any synchronized method or synchronized code block.
Now a multithreaded class X needs to call some method of this object, but in a thread safe manner. By putting call to the any method of A in synchronized(A) block as given below, any thread T of X would be able to do so if and only if, no other thread is executing any methods of that object.
synchronized(A) {
A.anyMethod();
}

To synchronize any method, use following syntax:

synchronized returnType methodName(arguments)
{
// statements to be synchronized
}