Synchronize On Events

last modified: August 15, 2014

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:

Doesn't always protect mutable state of the object sufficiently (because of the different locks in use).

Doesn't check for conditions already being true (which doesn't apply to all conditions, of course).


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


Loading...