Volatile Variable in Java

This post describes my experience working with Volatile Variable in Java. It is crucial in doing multithreading and distributed computing in Java.

“Volatile” is a modifier for a variable V forces each thread to read the value of V from the memory instead of the cache. In effect, you get the following features (cited from Wikipedia)

  1. (In all versions of Java) There is a global ordering on the reads and writes to a volatile variable. This implies that every thread accessing a volatile field will read its current value before continuing, instead of (potentially) using a cached value. (However, there is no guarantee about the relative ordering of volatile reads and writes with regular reads and writes, meaning that it’s generally not a useful threading construct.)
  2. (In Java 5 or later) Volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex.[9]

This is all very abstract. Next I will explain more with a few concrete examples that I ran into implementing an efficient multithreaded mapper in Hadoop MapReduce system.

One scenario is that we have multiple threads adding elements to an ArrayList or Hash map  If we want all the threads to see the ArrayList or HashMap with the right size, we need to use the volatile modifier. Otherwise, we might not (in the case that there is an outdated cached copy) see an updated size count. 

Same goes for a volatile integer. If we declare it as volatile, then if one thread modifies the value of a integer, all other threads will sure see the change.

Advertisements
This entry was posted in Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s