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.
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):
load
ing data.dup
operation.iadd
operation in the VM.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).