Safe publication : A secret to reveal

Programming in a multithread environment has never been simple and certainly not in java.  If you have already some experience with threads synchronization, you will certainly agree.  The problem is that most of the code we write should run in a multi thread environment (think to J2EE) and because computers tends to have more and more parallel CPUs, we can expect to write even more multithread code in the future.

So, it is difficult.

But there is fortunately a secret potion to solve that!  Brian Goetz revealed this “secret” in his book “Java Concurrency in Practice” (JCP for the initiated).  If you read this book, and get into the confidence, you will understand why, for example, the Double-check idiom (http://en.wikipedia.org/wiki/Double-checked_locking) is broken.

Let me reveal just a part of the secret:  Java multithread programming is not just about protecting your code about concurrent modification (what I thought before getting in the confidence).  It is about managing properly the memory, and making safe publication.

Every thread that create an object or write something in memory that will be used by another thread must make sure that the object is safely published to the other thread.  The “secret” revealed by Goetz is that java.concurrency package provides some tools to do that.  The others tools you can use are the class static initialization, the final fields, the volatile fields and finally proper handshaking with synchronized locks.

Before I read this book, I was thinking I knew how to write thread safe code.  I have to admit that I have put in production multithread code without knowing what a memory barrier is.  Thanks to this book, I know now that this code was probably broken.  If you write code, please don’t make the same mistake.   Be sure you know what a safe publication is before sharing objects accross thread.

The JCP book will explain you this.  If you have other good sources, thanks to share it with us.

Leave a comment

Filed under craftmanship

Leave a comment