Talk:Java Monitor
From APIDesign
@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