In a program written in the Java language. Sometimes in order to improve the execution efficiency of the program, the compiler will actively optimize its own, the frequently asked variables cached, the program when reading this variable may be directly from the cache (such as registers) to read this value. Instead of going to the memory to read. One advantage of this is that it improves the execution efficiency of the program, but when multi-threading programming is encountered. The value of the variable may be changed by another thread, and the value of the cache does not change accordingly, resulting in inconsistencies between the values that the application reads and the actual variable values. For example, in this thread, when reading a variable, in order to improve access speed, the variable will be read into a cache, and when the value of the variable later, it is directly from the cache to take the value. When the value of a variable changes in the line thread, the new value of the variable is copied to the cache at the same time, so that it remains consistent.
Volatile is a type modifier (typespecifier). It is designed to modify variables that are visited and changed by different threads. Variables defined by the volatile type are extracted directly from the corresponding memory each time the system uses it, rather than using the cache. After using the volatile modifier member variable, the values of the variables that all threads see at any time are the same. A demo sample using volatile is given below.
public class mythread Impl ements Runnable { private volatile Boolean flag; public void Stop () { flag = false; } public void Run () { while (flag) / /do something } } |
The above code demonstrates that the sample is a way to stop threads from being used most often. Assuming that a Boolean variable flag is not declared volatile, then, when the thread's Run method infers the flag value, it is possible to use the value in the cache, so that the operation of flag by other threads cannot be obtained in a timely manner. This causes the thread not to stop in time.
It is important to note that because volatile does not guarantee the atomicity of the operation, volatile is not a substitute for sychronized in normal circumstances. In addition, using volatile prevents the compiler from optimizing the code, thereby reducing the execution efficiency of the program. So unless there is a compelling reason. Otherwise. Can not use volatile. Try not to use volatile.
From the new book "Java Program ape interview written book" Official website
What is the volatile effect of the Java Program Ape interview written book?