What is the meaning of volatile java

http://southking.javaeye.com/blog/438318

        We know that in Java action set variable values, in addition to long and double outer type of variables are atomic, that, for the variable values simply read and write operations is no need for synchronization.         This JVM 1.2 before, the Java memory model implementation always read a variable from main memory, it does not require any special attention. With the JVM mature and optimized, now in a multithreaded environment volatile keyword becomes very important.         In the current Java under the memory model, the variables can be stored in thread local memory (such as machine registers), rather than directly in the read and write main memory. This modification may result in a thread in the main memory of the value of a variable, while the other thread to continue using its copy of the variable's value in the register, resulting in inconsistent data.         To solve this problem, just like in this program, to the variable is declared as volatile (unstable) can, which indicate the JVM , this variable is unstable, every time you use it all went to the main memory read. In general, the sign shared among the tasks in a multitasking environment should be added volatile modification.         Volatile

 
 
Modified member variable each time it is accessed threads are forced to re-read the value of the member variable from shared memory. Also, when members of the variable changes, forcing thread will change the value written back to the shared memory. So that at any moment, two different threads always see the same value of a member variable.          Java language specification states: compare the original value in order to obtain optimum speed, allowing the private copy threads save the shared member variable, but only if the thread when entering or leaving the synchronized block with shared member variable.        So when multiple threads at the same time interacting with an object, it must be noted that the thread to make timely changes to get shared member variable.        The volatile keyword is prompted VM : For this member variable can not save its private copy, but should interact directly with the shared member variable.       Suggested Use: Use on a member variable two or more threads access volatile . When the variable to be accessed has been synchronized during the constant code block, or is not necessary to use.       Due to the use of volatile shut off VM in the necessary code optimization, it is relatively low in efficiency, so be sure to use this keyword only when necessary.
 
 
 
 

Published 18 original articles · won praise 16 · views 390 000 +

Guess you like

Origin blog.csdn.net/f_zongjian/article/details/5722354