Skip to main content

Concurrency and Java Memory Model

Posted by mortazavi on May 17, 2006 at 5:08 PM PDT

The master craftsmen of memory management in concurrent programing (William Pugh, Univ. of Maryland, and Jeremy Manson, Purdue University) have advice worth following by every programmer of multi-threaded Java code.

The session included a couple of interesting multi-threaded puzzlers that arise due to compiler and processor oprimization of threads and serialization of operations and a mention of the famous "happens-before ordering" and its
transivity, imposed by locks.

The speakers discussed the value of the "volatile" modifier — Reads and writes of volatiles are atomic. Volatile writes and reads cannot be reordered by compilers. Effectively, volatiles must be accessed through
acquire/release pairs. Volatiles are useful when writing non-blocking
code. An alternative to volatile is java.util.concurrent.Atomic.

Other advice:

Do a web search on 'double check locking'.

Lessons learned:

Declare all fields of immutable classes as final.

Be "scared" enough of multi-threaded code to make you fully cautious!

Imagine thread schedulers are out to get you.

And, I guess to reduce the possibility of the more interactable cases, they advised that programmers

Reduce lock scope.

Reduce lock duration.

Other resources:

www.cs.umd.edu/~pugh/java/memoryModel

Goetz's book was mentioned again, too.