I. Volatite Brief INTRODUCTION
The Java language provides a slightly weaker synchronization mechanism, the volatile variable. Used to ensure that updates to variables are notified to other threads, ensuring that new values are immediately synchronized to main memory, and flushed from main memory immediately before each use. When a variable is declared as a volatile type, the compiler and the runtime will notice that the variable is shared.
Two. Volatite thread safety?
Volatile variables are immediately visible to all threads, and all writes to volatile variables can immediately be reflected in other threads, in other words: Volatile variables are consistent across threads, so operations based on volatile variables appear to be thread safe. This view is wrong!
Three. Why is Volatite thread unsafe?
[Java]public class volatiletest{public static volatile int i;public static void increase () { i++;}} [/java]
Javap-c-L Volatiletest.class
[Java]public class Volatiletest {public static volatile int i;public volatiletest (); code:0: aload_01:invokespecial #1//Method java/lang/object. "":() V4:returnLineNumberTable:line 1:0public static void increase (); code:0: getstatic #2//Field i:i, the value of I is taken to the top of the Operation Stack, and the volatile is guaranteed to be correct at this time. 3:iconst_14:iadd//increase, but other threads may have increased the I value a lot at this time 5:p Utstatic #2//Field i:i, the I value of this already out of date is synchronized back to main memory, and I value is destroyed. 8:returnlinenumbertable:line 6:0line 7:8}[/java]
In this sense, volatile is not entirely thread-safe, although volatile variables are atomic when read and saved, but the self-increment and decrement operations are synthesized by multiple operations, which are not atomic operations.
Java Concurrency Programming-volatile