Friday, March 16, 2012

What is AtomicReference for really?

we had a discussion about AtomicReference at work the other day, it appears that none of us really understand why we should use AtomicReference based on a quick glimpse at the java doc provided.

The confusion comes from that we all firmly believe reference assignment is atomic in java, so why both with AtomicReference.

I decided to do some research on it and found this great post: Memory Barriers. It looks like there are several benefits of using AtomicReference.

Internally AtomicReference marks the value volatile, which creates a memory barrier that a, makes sure no thread is reading out dated data, b, provides happens-before guarantee because your code won't be reordered by compiler. If you only use the get/set method of AtomicReference, you are essentially marking your variable volatile in a fancy way.

The other interesting method is compareAndSet(expected, newVal). With care, AtomicReference can be used as an efficient way to do synchronization, especially when concurrent change happens rarely. to do this, the thread calls compareAndSet instead of set. If it fails, then it means that the value had been updated, so this thread has to deal with the conflict, such as abandon its change, overwrite, or merge.

In summary, AtomicReference differs from other atomic types in the concurrency package that it doesn't offer the typically desired atomic action like getAndIncrement, but they are similar that they all provide compareAndSet methods.