What does volatile actually do in Java?

Volatile to many that code in Java is a mystery keyword. Most keywords are really simple to understand, but volatile to many is defined by a lot of mathematical mumbo-jumbo. Volatile is a very very simple structure, if explained right:

Writes happen-before reads.

Still a little confused? There are three basic problems in the Java (or any other) multi-threaded environment:

  1. Each CPU (real or virtual) may have it’s own small cache of memory data
  2. Any compiler along the way (including Javac, or one of the Hotspot compilers) may change the order of instructions to improve performance
  3. You have no real idea of which instructions in another thread will run before or after those in any other thread

As a result of these problems your update to a field may not be seen by another thread for some arbitrary amount of time, in fact it may exit before seeing your changes. Enter the volatile modifier. It’s job is to guarantee “happens-before” behavior. This means three things:

  1. Write operations are executed before read operations.
  2. Compilers are not allowed to re-order accesses to the field.
  3. Caches must be flushed before reading the field

The combination of these guarantees means essentially that a “read” of the field will always give the “latest” state of the field. When a new value is written, any subsequent reads (including those scheduled to “happen at the same time”) will see the new value.

Advertisements

2 Responses to “What does volatile actually do in Java?”

  1. Declaring things final in Java « Techno Lemming Says:

    […] final keyword can serve as a hint to the Hotspot compiler at runtime. In some ways the opposite to volatile. There is another, much more important reason to declare fields, variables and parameters (almost […]

  2. PAFU-PAFU Says:

    Hey brother,

    I think there is a more simple way to explain it:

    A volatile variable allows to became this variable always up to date for Threads. So it can be used only if this threads make simple operations over this variable such as read or write only (but never both). A volatile variable is never locked such synchronized members, but when a thread look for this variable, it will conciliate its value with master copy from memory (the cache like you said).

    I’m only posting it because this was more simple for me.

    I hope I can sum your post with this little comment.


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

%d bloggers like this: