Witscale Test Center

12.3 Access to shared data/code with synchronization > 12.3.2 How does the synchronization work?


12.3.2 How does the synchronization work?

Every object in Java has a built-in lock. It comes into play only when the object has synchronized code.  This lock symbolizes the authority to execute the synchronized code. Therefore, whenever a thread encounters a synchronized code during execution, it must acquire this lock.  Since there is only one lock per object, only one thread can own it at a time. Therefore, only one thread can execute the synchronized code at a time.  Once a thread has acquired the lock, no other thread can enter the synchronized code until the lock has been released.  Therefore if some other thread has to execute a synchronized methods on same object, it must wait until the lock is acquired by another code.  Figure 12.9 illustrates the sequence of events when a thread encounters a synchronized code on object. For example, a thread myThread invokes a synchronized method setAmountDue() on myAccount object.


 

 

Figure 12.9 Steps when a thread myThread encounters synchronized method (on object myAccount) during its execution

 

The thread holding the lock (that is the thread currently in the synchronized code) releases the lock when it exits the synchronized code. At that point, the lock (that is the authority to execute synchronized code) is available. Now the thread waiting for it or a thread that encounters the synchronized code on that object, can try to acquire it.

 

Programmatically you do not deal with locks . That means you need not write a code to acquire, release or manage it. Java’s threading support takes care of it. All you need to do is to declare the method and code (that must execute as one indivisible step) with the synchronized keyword. The acquiring and releasing of locks is transparent to you.