Friday 4 September 2015

What synchronization constructs does Java provide? How do they work?

The two common features that are used are: 

1. Synchronized keyword - Used to synchronize a method or a block of code. When you synchronize a method, you are in effect synchronizing the code within the method using the monitor of the current object for the lock. 

The following have the same effect. 

synchronized void foo() {
 

and
 
void foo() {
 
       synchronized(this) {
 
}

2. wait / notify.

wait() needs to be called from within a synchronized block. It will first release the lock acquired from the synchronization and then wait for a signal.

When somebody calls notify() on the object, this will signal the code which has been waiting, and the code will continue from that point. 

If there are several sections of code that are in the wait state, you can call notifyAll() which will notify all threads that are waiting on the monitor for the current object.

Remember that both wait() and notify() have to be called from blocks of code that are synchronized on the monitor for the current object.

No comments:

Post a Comment