[07] In java, volatile means ..

In this post we avoid when-to-use-volatile. When we say “long” we mean “long, and double, the 64bit types”.

* volatile is a field modifier
* visibility — fields marked “volatile” are never cached in a thread’s register
* Local variables (ie stack variables local to a method) are different from fields. Local variables are never shared with other threads so never need volatile modifiers

**** volatile long/double:
– is permitted by compiler
– volatile has an important atomicity effect on long/double fields
–> According to 3rd edition of the Java Language specification, declaring a long field to be volatile ensures that reads or writes to it occur atomically.
–> “Unless they are declared volatile, implementations of Java are allowed to treat assignments to long and double variables as two assignments to two variables that hold 32 bits each rather than one assignment to single variable that holds 64 bits.” — http://www.mindspring.com/~mgrand/double-checked_locking_implementation.html

**** In a nutshell, volatile helps visibility and also helps (for 64bit load/store) atomicity.
1) volatile helps visibility for all primitive fields including long and double.
1.1) longer story for reference types. There’s another blog post on this.
2) volatile’s help on atomicity is limited to 64bit field’s load and store
2.1) load/store on smaller data types are always atomic whether volatile or not. Guaranteed by the Java Memory Model.
2.2) For ANY data type, Composite read/write operations (like *=, ++ ) on volatile fields can compile but are non-atomic. A float volatile field is similar to a field of type VFloat:

final class VFloat { //from http://g.oswego.edu/dl/cpj/jmm.html and P97 [[concurrent programming in java]]
private float value;
final synchronized void set(float f) { value = f; }
final synchronized float get() { return value; }
}

One of the most frequent/important consequences of 2.2 is

Q: how to avoid another thread modifying/reading such a float variable half way through my increment?” (or another composite operation)
A: volatile can’t help. Synchronize please.

Advertisements

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s