Synchronize On Events

Change...

 public class NormalJavaWaitIdiom{
   Object monitor;
   boolean someState = false;
   boolean someOtherState = false;

public void someMethod(){ synchronized(monitor){ while(!someState) monitor.wait(); } }

public void someOtherMethod(){ synchronized(monitor){ while(!someOtherState) monitor.wait(); } }

public void notifySomeStateChange(){ synchronized(monitor){ someState = true; monitor.notifyAll(); } } }
into
 public class ProposedWaitIdiom
   Object notableEvent;
   Object otherNotableEvent;

public void someMethod(){ synchronized(notableEvent){ notableEvent.wait(); } }

public void someOtherMethod(){ synchronized(otherNotableEvent){ otherNotableEvent.wait(); } }

public void notifySomeStateChange(){ synchronized(notableEvent){ notableEvent.notify(); } } }


Pros:

Cons:


JavaLanguage concurrency sure is "subtle". These two examples have very different semantics:

Maybe what's needed is a third version, which is like one of these but with a clear statement of what it's supposed to do, and code that matches it :-). -- LukeGorrie


CategoryJava CategoryConcurrency CategoryEvents


EditText of this page (last edited August 15, 2014) or FindPage with title or text search