Java Keywords (Part XXII): volatile

Java keyword list

abstract continue for new switch
assert default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp volatile
const* float native super while
Keyword marked with an asterisk (*) are keywords that, although valid, are not used by programmers.
In the last article, we learned about the use of synchronized keyword, and we scratched the surface a little bit about concurrency. The keyword volatile is also relevant in concurrency. To learn more about why this keyword is applicable to concurrency, please read about Atomic Access. You could also read the Threads and Locks section of the Java Specification.

As we learned before, the Java programming language allows threads to access shared variables. To ensure that shared variables are consistently and reliably updated, a thread should ensure that it has exclusive use of such variables by obtaining a lock that enforces mutual exclusion for those shared variables. The previous article covered the use of the keyword synchronized for this purpose. You could use synchronized methods or synchronized statements to achieve this. However, Java provides a second mechanism: volatile fields or variables. This is actually more convenient than locking in some cases. As a reminder, this article is only to show how to use the keyword, not why you should use it. To learn the why, please visit the sites I provided. That said, I will point out that a field may be declared volatile, in which case the Java Memory Model ensures that all threads see a consistent value for the variable. Also, it is a compile-time error if a final variable is also declared volatile. In other words, constants need not to be marked as volatile.

The keyword volatile is one type of Java's field modifiers. Throughout this series, you learn about other fields modifiers such as static, and final. Ths article covers volatile, and the next will cover transient. To use volatile, simply add it after a variable's access modifier like this:

BAD USE:


final volatile int MY_CONSTANT = 3; // THIS IS A COMPILE-TIME ERROR!! 
GOOD USE:

static volatile int myVariable = 3; // THIS IS OK!! 
private volatile SomeClass otherVariable = new SomeClass(); // THIS IS ALSO OK!!
Basically, volatile can be used with primitive or non-primitive fields as field modifier, and combined with other field modifiers, except for final. Next up, Part XXIII: transient

Comments

Popular posts from this blog

Combining State and Singleton Patterns to Create a State-Machine

Exception Handling: File CRUD Operations Example

The Beauty of the Null Object Pattern