Talk:Java Monitor

From APIDesign

Revision as of 12:56, 31 January 2010 by JaroslavTulach (Talk | contribs)
Jump to: navigation, search

@Synchronized does look good for some cases. However, it does not address (at least not without writing just as much code as doing it without annotations) a second class of monitor usage bugs that I find is very common: Using a single lock for multiple resources. It is very common to see a pattern such as:

public class Foo {
  private Bar bar;
  protected synchronized replaceBar() {
     bar = new Bar(xyz);
  }
  public synchronized Bar getBar() {
     return bar;
  }
  public synchronized void addPropertyChangeListener (PropertyChangeListener pcl) {
     ...
  }
  public synchronized void removePropertyChangeListener (PropertyChangeListener pcl) {
     ...
  }
 }

While this code is correct in that it will compile and run as the user expects,

  1. There is much greater potential for deadlocks, and
  2. An application with such code can have thread liveness problems

because the same monitor is being used to protect two unrelated resources from access collisions.

-Tim Boudreau

Right, this is the behavior. But it is not flaw of Java Monitor, it is a design decision of the inventor of monitor concept. The appropriate solution would be to put the separate concept into separate records/classes. So Java is using the monitor concept correctly (in this case), but one may treat this as another indication that monitors are not really suitable for OOP.

--JaroslavTulach 12:56, 31 January 2010 (UTC)

Personal tools
buy