'. '

Talk:Java Monitor

From APIDesign

Revision as of 12:52, 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

Personal tools
buy