Home > Blogs > Synchronized Reads

Synchronized Reads

By  Aug 2, 2008

Topics: Programming, Java

This is my first post on Java Concurrency in Practice. It is all about guarding reads to shared data and the epiphany that this concept was to me.

This book is highly regarded in the Java word, and for good reason. I must admit that I have seen Brian Goetz speak about concurrency, so some of the material is not exactly new to me. For example there is this:

For each mutable state variable that may be accessed by more than one thread, all accesses to that variable must be performed with the same lock held. In this case, we say that the variable is guarded by that lock.

The emphasis is from the text. Actually in the text, this is also in a grey-box. To be perfectly honest, I really dislike this style of writing. Good writers should not need tricks like background colors and italics to emphasize a point. Good writing is all about accomplishing that emphasis via the expressive power of the English language (or whatever language the writer is using.) I digress.

Writing style aside, this is a powerful statement. In fact I believe I first saw it in a slide by Goetz. The book talks about a common mistake of only guarding your shared variables during write operations. I know that I have in fact made that mistake. Chapter 3 of the book has some excellent points on this.

The code in Listing 3.1 shows one thread waiting on another thread. The second thread must write a value of a shared variable and set a flag. Only after the flag is set can the first thread then print out the value and exit. The lack of synchronization allows for an infinite loop to happen or even an incorrect value to be read.

The section on non-atomic 64-bit operations was even more eye opening. The prospect of getting the low 32-bits of one value and the high of another because of concurrent access is mind blowing. That is pure garbage, not just an infinite loop or a default value or something like that.

As chilling as that is, it gets even more nauseating when you think about the kind of bugs that it could lead to. Think about the symptoms of such a bug. It would probably happen infrequently and be nearly impossible to reproduce. That is bad. But then it would lead you to look for code that could be setting garbage values, i.e. code that brings in “foreign” data with not enough validation. You would never assume that the garbage data is internal because if it was, it would rear its ugly head in multiple places and you could track it down. It would have to be external. Of course such a search for the cause of the bug would just be a suicide inducing waste of time.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.