multithreading - Java synchronization on Object. Why doesn't this deadlock? -


the construct below works , want, want understand why doesn't deadlock.

the example below makes sure user has clicked on yes or no on joptionpane box pops (on edt) prior carrying on.

package waitexample;  import javax.swing.joptionpane; import javax.swing.swingutilities;  public class waitexample {      public static void main(string[] args) throws interruptedexception {         system.out.println("starting");         object mywaiter = new object();          swingutilities.invokelater(() -> {             system.out.println("invoked");                         joptionpane.showconfirmdialog(null, "message", "title", joptionpane.yes_no_option);             synchronized (mywaiter) {                 system.out.println("calling notify");                 mywaiter.notify();                 system.out.println("notified");             }         });          synchronized (mywaiter) {             system.out.println("waiting");             mywaiter.wait();             system.out.println("done waiting");         }          system.out.println("ending main()");     } } 

but looks entering synchronized(mywaiter) blocks @ same time different threads, given following output:

starting waiting invoked calling notify notified done waiting ending main() 

why doesn't deadlock?

quoting documentation wait,

the thread releases ownership of monitor , waits until thread notifies threads waiting on object's monitor wake either through call notify method or notifyall method. thread waits until can re-obtain ownership of monitor , resumes execution.

this explains lines

starting waiting invoked <- have appeared before or after waiting 

and quoting documentation of notify,

the awakened thread not able proceed until current thread relinquishes lock on object. awakened thread compete in usual manner other threads might actively competing synchronize on object; example, awakened thread enjoys no reliable privilege or disadvantage in being next thread lock object.

this explains

calling notify notified 

since @ point edt thread abandons synchronized block , releases lock, next lines follow:

done waiting ending main() 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -