J2EEOnline J2EE






Threading Model   «Prev  Next»
Lesson 7Synchronization
ObjectiveDescribe how access to shared objects is synchronized among multiple threads.

Synchronizing Shared Java Objects

Since objects are often shared among multiple threads, it is important that access to these objects be coordinated. Otherwise, you could run into situations where one thread is updating an object while another thread is trying to use it. The coordination of thread access to shared objects is referred to as synchronization.
Synchronization applies to classes as well as objects.

Thread A starts object update

Synchronization Concept
Place your Mouse Pointer above the arrowed lines between the objects in the diagram. As this diagram demonstrates, without synchronization[1] one thread may try to read an object while it is in the process of being updated. This usually results in bad data being supplied to the reader (data corruption).


Java support

Java supports synchronization through synchronized methods and synchronized statements. A synchronized method is declared by putting the synchronized keyword in the method's declaration.
For example, the following declares myMethod() as being synchronized:

public synchronized void myMethod() {
  . . .
}

One synchronized method per object

Only one synchronized method can be invoked for an object at a given point in time. This method must return before any other synchronized methods can be invoked for that object.
Synchronization is maintained through the use of locks (also referred to as monitors[2] ).
Every object and class is associated with a unique lock[3]. When thread A invokes a synchronized method of an object or class, it must wait for the lock associated of that object or class. If another thread, thread B, has acquired the lock, then thread A enters the waiting state until the lock becomes available.


Thread Invokes Synchronized Method
A synchronized statement is similar to a synchronized method except that it applies to a single statement block instead of an entire method. Synchronized statements are declared using the following syntax:
synchronized (object) {
 statement(s)
}

A thread must acquire the lock of the object before executing the synchronized statement. It relinquishes the lock once the synchronized statement has completed.

Synchronization Concepts - Quiz

Click the Quiz link below to check your understanding of synchronization concepts.
Synchronization Concepts - Quiz
[1] Synchronization: The coordination of multi-thread access to shared objects.
[2] Monitor: A mechanism for implementing shared access to an object, also referred to as a lock.
[3] Lock: A mechanism for implementing shared access to an object. Also referred to as a monitor.