Search code examples
javavolatile

A quote from "Java Threads" book about volatile keyword


I was just wondering if someone could explain the meaning of this:

Operations like increment and decrement (e.g. ++ and --) can't be used on a volatile variable because these operations are syntactic sugar for a load, change and a store.

I think increment and decrement should just work fine for a volatile variable, the only difference would be every time you read or write you would be accessing from/writing to main memory rather than from cache.


Solution

  • The Java Language Specification does not have atomic operations for the ++ and -- operators. In other words, when you write code in the following manner:

    a++;
    

    the Java compiler actually emits code that is similar to the set of steps below (the actual instructions will vary depending on the nature of the variable):

    1. Load the operand onto the stack using one of the operations for loading data.
    2. Duplicate the value of the operand on the stack (for the purpose of returning later). This usually accomplished using a dup operation.
    3. Increment the value on the stack. Usually accomplished using the iadd operation in the VM.
    4. Return the value (obtained in step 2).

    As you can observe, there are multiple operations in the VM for what is commonly thought to be an atomic operation. The VM can ensure atomicity only upto the level of an individual operation. Any further requirement can be achieved only via synchronization or other techniques.

    Using the volatile keyword, allows other threads to obtain the most recent value of a variable; all read operations on a variable will return the recently updated value on a per-instruction basis. For example, if the variable a were to be volatile in the previous example, then a thread reading the value of a would see different values if it were to read a after instruction 2 and after instruction 3. Use of volatile does not protect against this scenario. It protects against the scenario where multiple threads see multiple values for a after instruction 2 (for instance).