Deep analysis of volatile in Java threads

Source: Internet
Author: User

VolatileKey Words

Usually read the JDK source code, often see the source code has written variable by the volatile keyword decoration, but it is not very clear what is the use of the keyword, and now finally clear, then I would like to say this volatile what is the use of it.

When a variable is defined as volatile, this variable is guaranteed to be visible to all threads, that is, when a thread modifies the value of the variable, the new value of the variable is immediately known to other threads. It can be understood that all write operations on volatile variables are immediately known to other threads . However, this does not mean that operations based on volatile variables are safe in concurrency, because volatile only guarantees memory visibility, but does not guarantee the atomicity of variable operations. For example, the following code:

/** * Initiates 20 threads, each of which has 10,000 self-increment operations on the race variable, and if the code is capable of concurrency correctly, the result of the final race should be 200000, but the actual run result is less than 200000. *  * @author Colin Wang * */public class Volatiletest {public static volatile int race = 0;public static void Increase ( ) {race++;} private static final int threads_count = 20;public static void Main (string[] args) {thread[] THREADS = new Thread[threads_  count];for (int i = 0; i < Threads_count; i++) {threads[i] = new Thread (new Runnable () {@Overridepublic void Run () {for (int i = 0; i < 10000; i++) {increase ();}}); Threads[i].start ();} while (Thread.activecount () > 1) thread.yield (); System.out.println (race);}}

This is because the race++ operation is not an atomic operation, causing some threads to lose changes to the variable race. To use the Volatale variable, you typically meet the following two scenarios:

    1. The result of a variable's operation does not depend on the current value of the variable, or can guarantee that only a single thread modifies the value of the variable.
    2. Variables do not need to participate in invariant constraints with other state variables.

The use of volatile variables can also prevent the JIT compiler from ordering the command reordering optimizations, where a singleton pattern is used to give an example:

/** * Singleton mode routine One *  * @author Colin Wang * */public class Singleton_1 {private static singleton_1 instance = Null;private Singleton_1 () {}public static singleton_1 Getinstacne () {/* * This implementation was judged two times by Instance==null, which is the double check lock of the singleton mode. * The first check is that if an object instance has already been created, it is returned directly without needing to enter the synchronization code again. * Otherwise the synchronization thread is started, and after entering the critical section, the second check is that: * If one of the synchronized threads has created an object instance, the other threads will no longer have to create the instance. */if (Instance = = null) {synchronized (Singleton_1.class) {if (instance = null) {/* * still exists: The following code is not an atomic operation, the JVM executes this line of code , it is decomposed into the following actions: * 1. Allocate memory to instance, allocate and initialize to NULL in the stack * 2. Call the constructor of singleton_1, generate an object instance, and allocate  * 3 in the heap. Point instance to the object allocated in the heap * Because of command reordering optimizations, execution order may become 1,3,2, * then when a thread finishes executing 1, 3, is preempted by another thread, * then instance is not null and will return directly. * However, 2 has not been executed, which means the object instance has not been initialized yet. */instance = new singleton_1 ();}}} return instance;}}


/** * Singleton mode Routines two *  * @author Colin Wang * */public class Singleton_2 {/* * In order to avoid the JIT compiler's instruction reordering optimizations for code, you can use the volatile keyword, * through this A key also allows the variable not to have replicas in multiple threads, which can be thought of as being read directly from main memory, equivalent to implementing a lightweight lock. */private volatile static Singleton_2 instance = Null;private singleton_2 () {}public static singleton_2 Getinstacne () {if (instance = = null) {synchronized (Singleton_2.class) {if (instance = = null) {instance = new singleton_2 ();}}} return instance;}}


After a variable has a volatile modifier, changes to the variable are protected by a memory barrier, so that subsequent instructions cannot be reordered to the position before the memory barrier. The read performance of the Volalite variable is similar to that of a normal variable, but the write performance is lower because it requires inserting a memory barrier directive to ensure that the processor does not run out of order. Even so, the total cost of volatile in most scenarios is still lower than the lock, so volatile semantics can satisfy demand when choosing volatile is better than using locks.

Deep analysis of volatile in Java threads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.