Talk:Java Monitor
From APIDesign
(Difference between revisions)
(Comment re using one monitor to protect unrelated resources) |
|||
Line 1: | Line 1: | ||
@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: | @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: | ||
+ | <source lang="java"> | ||
public class Foo { | public class Foo { | ||
private Bar bar; | private Bar bar; | ||
Line 16: | Line 17: | ||
} | } | ||
} | } | ||
+ | </source> | ||
While this code is correct in that it will compile and run as the user expects, | While this code is correct in that it will compile and run as the user expects, |
Revision as of 12:52, 31 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,
- There is much greater potential for deadlocks, and
- 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