A quote from the Java Threads book about the volatile keyword

I'm just wondering if anyone can explain the meaning of this:

Operations such as increment and decrement (for example, ++and --) cannot be used for a volatile variable, because these operations are syntactic sugar for loading, modifying and storing.

I think increment and decrement should work just fine for a volatile variable, the only difference would be each time you read or write, you will access from / write to main memory, not from cache.

+3
source share
5 answers

Java ++ --. , :

a++;

Java- , ( ):

  • , load.
  • ( ). dup.
  • . iadd .
  • ( 2).

, VM , . VM . .

volatile, ; . , a , , a, , a 2 3. volatile . , a 2 ().

+3

volatile visibility. atomicity. , .

+8

, .

, ++ -- . .

volatile , , .

++ -- , , , .

a = a + 1 () , , () , a++ .

+7

opeartion, .

, , , , - . , , , . , , , , , .

, .

+1

No - you use "volatile" to indicate that a variable can be modified by an external object. Usually it will be some JNI C code, or a special register associated with some equipment, for example, with a thermometer. Java cannot guarantee that all JVMs on all architectures may be able to increment these values ​​in a single machine cycle. Therefore, it does not allow you to do this anywhere.

0
source

All Articles