Java Question:
Exiting the synchronization block automatically notifies All (). Is this expected behavior?
I tested it, and it seems to me 1. When the execution exits the synchronization block, it automatically notifies All () 2. When the method itself is synchronized, it automatically notifies () when it returns. (Not notifyAll ())
The code:
public class Test { public static void main(String[] args) throws InterruptedException { MyThread lock = new MyThread(); new WatingThread(lock,1).start(); new WatingThread(lock,2).start(); //above tow threads would start and then wait for a lock lock.start(); } } class MyThread extends Thread { public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("MyThread is trying to acquire the lock .."); synchronized (this) { System.out.println("MyThread has acquired the lock !!"); System.out.println("MyThread is Coming out of synch block.."); } System.out.println("MyThread has released the lock !!"); } } class WatingThread extends Thread { private Object lock; private int id; public WatingThread(Object lock, int id ) { this.lock = lock; this.id = id; } @Override public void run() { System.out.println(String.format("[%d] : Check if lock is available ...",new Object[]{id})); synchronized (lock) { System.out.println(String.format("[%d] : Acquired the lock !!",new Object[]{id})); try { System.out.println(String.format("[%d] : Going to wait on lock.. ",new Object[]{id})); lock.wait(); System.out.println(String.format("[%d] : Got notified !!!",new Object[]{id})); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(String.format("[%d] :I am done !!",new Object[]{id})); } } }
code>
Conclusion:
[2]: check if the lock is free ...
[2]: I got a castle!
[1]: Check if the lock is free ...
[2]: Wait until it is locked.
[1]: I got a castle!
[1]: Waiting for a lock.
MyThread is trying to get a lock.
MyThread has acquired a castle!
MyThread exits the sync block.
MyThread has released a lock!
[1]: Received a notification !!!
[1]: I am done !!
[2]: Received a notification !!!
[2]: I am done !!
source share