The volatile keyword in Java

Source: Internet
Author: User
Tags volatile

The role of the volatile keyword is to ensure the synchronization of multi-threaded execution.

In the memory model of the Java Virtual machine, there is the concept of main memory and working memory, each thread corresponds to a working memory and shares the data of main memory, let's see what is the difference between manipulating the normal variable and the volatile variable:

1, for ordinary variables: read operation will first read the work memory data, if not in the working memory, copy a copy of the data from the main memory into the working memory; The write operation modifies only the copy data of the working memory, in which case the other threads cannot read the latest value of the variable.

2, for volatile variables, read operation JMM will be the corresponding value in the working memory is invalid, requires the thread to read the data from the main memory, the write operation jmm the corresponding data in the working memory to the main memory, in which case, other threads can read the latest value of the variable.

The memory visibility of volatile variables is based on memory Barrier, what is a memory barrier? A memory barrier, also known as a memory fence, is a CPU instruction. In order to improve execution performance while the program is running, the compiler and the processor reorder the instructions, JMM, to ensure the same results on different compilers and CPUs, by inserting specific types of memory barriers to suppress certain types of compiler reordering and handler reordering, Inserting a memory barrier tells the compiler and the CPU: No instructions can be reordered with this memory barrier instruction.

In order to improve processing performance, the CPU does not directly communicate with the memory, but instead reads the memory data into the internal cache (L1,L2), but the operation is not determined when it is written back to memory, if the volatile variable is written, when the CPU executes to the lock prefix instruction, Will write the data of the cache row of this variable to memory, but there is still a problem, even if the memory data is up-to-date, the other CPU cache or the old value, so in order to ensure the cache consistency of each CPU, each CPU by sniffing the data propagated on the bus to check their cached data validity, When the data of the memory address corresponding to the cache row is found to be modified, the cache row is set to an invalid state, and when the CPU reads the variable, the cache row is set to invalid and the data is re-read from memory to the cache.

While the program is running with CPU, cache, and memory three parts working together, thread a reads the variable x in memory into the cache, and thread B now modifies the variable x. Although the x in memory has changed, thread A still thinks that the x in the cache is up to date. This affects the synchronization between threads.
The purpose of the volatile keyword is that if thread B modifies the variable x, the x in the high-slow of thread A is invalidated and needs to be reloaded from memory.

The use of volatile in singleton mode is more prudent, this singleton implementation is called "double check", before entering the synchronized area to check once, enter and then check again. The outer if can prevent all threads from entering the synchronized area, thus avoiding the thread waiting for a lock at the same time, and the If for the inner layer to be used for accurate judgment, lest other threads have created a singleton.

class Singleton {    privatevolatilestatic Singleton instance;    publicstaticgetInstance() {        ifnull) {            syschronized(Singleton.class) {                ifnull) {                    newSingleton();                }            }        }        return instance;    } }

A new method of single-instance pattern implementation based on class loading mechanism

publicclass Singleton {      staticclass SingletonHolder {          staticnewSingleton();      }            publicstaticgetInstance(){          return SingletonHolder.instance;      }  }
Resources

Https://www.jianshu.com/p/195ae7c77afe
http://www.importnew.com/27863.html#comment-638620

The volatile keyword in Java

Related Article

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.