JavaOne

EnfranchisedMind's Adventures at JavaOne 
« Back to blog

Concurrency Gotchas 2

Whole series of bugs associated with synchronized issues.
 
 
synchronized(null) { // NPE
 
synchronized(obj) {
  obj = new MyObject(); // Undermined synchronization
}
 
private static final String LOCK = "LOCK";
synchronized(LOCK) { // Interned strings use the same lock elsewhere
 
 
private static final Integer LOCK = 0;
synchronized(LOCK) // Same as string issue
 
// ReentrantLock FAIL
final Lock lock = new ReentrantLock()
synchronized(lock) {
 
Should be:
 
final Lock lock = new RentrantLock()
lock.lock()
try {
 
} finally {
  lock.unlock()
}
 
 
You should lock on the variable being protected, or an explicit lock object (new Object())

Loading mentions Retweet

Comments (0)

Leave a comment...

 
Got an account with one of these? Login here, or just enter your comment below.
Posterous-login    Connect    twitter