JavaOne

EnfranchisedMind's Adventures at JavaOne 
« Back to blog

Concurrency Gotchas 5

Safe publication: don't escape before constructor finishes running. Most common example is to register yourself as a listener in the constructor. Starting a thread in a constructor is also bad (usually a cleaner/maintainer). Static factory methods are the solution.
 
Coordination: threads and wait/notify. Don't use stop, suspend, resume, destroy, run on Thread. ThreadGroups are also now passe.
 
To do wait/notify, you need to synchronize on the same lock. Important to check the condition in a while loop, because wait may not have actually been notified. And make sure the condition is satisfied. [And make sure the condition is volatile or otherwise ensured to be visible. -ed]
 
Performance: Deadlock. To avoid it: lock splitting (divorce locks and do not take locks at the same time), lock ordering (classic), lock timeout (via ReentrantLock), tryLock (nonblocking via Reentrant). SpinWait. i.e. "while(!flag) { Thread.sleep(100) }" -- you really want wait/notifyAll. Lock contention is also a problem: most data structures can break themselves down into a number of distinct partitions ("Lock Striping").
 
Then shared some particularly naughty code he found in Hibernate.

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