Talk:Java Monitor

From APIDesign

(Difference between revisions)
Jump to: navigation, search

Tim (Talk | contribs)
(Comment re using one monitor to protect unrelated resources)
Next diff →

Revision as of 04:41, 29 January 2010

@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