Role of the keyword volatile in Java

Source: Internet
Author: User

Role of the keyword volatile in Java

Used in multithreading and synchronization of variables. To improve the efficiency, the thread copies A member variable (such as A) (such as B), and the access to A in the thread is actually B. Only A and B are synchronized in some actions. Therefore, A and B are inconsistent. Volatile is used to avoid this situation. Volatile tells jvm that the modified variables do not keep copies and directly access the primary memory (that is, A mentioned above)

In the Java memory model, there is main memory, and each thread also has its own memory (such as registers ). For performance, a thread maintains a copy of the variable to be accessed in its own memory. In this case, the value of the same variable may be different from the value of another thread's memory or the value in main memory at a certain moment.

If a variable is declared as volatile, it means that the variable is modified by other threads at any time, so it cannot be cached in the memory of the thread. The following example shows the role of volatile:

Public class StoppableTask extends Thread {private volatile boolean pleaseStop; public void run () {while (! PleaseStop) {// other operations to be performed...} public void tellMeToStop () {pleaseStop = true ;}}

If pleaseStop is not declared as volatile and check its own copy when the thread executes run, it cannot be found that other threads have called tellMeToStop () to modify the pleaseStop value.

Volatile generally cannot replace sychronized, because volatile cannot guarantee the atomicity of operations. Even if it is just I ++, it is actually composed of multiple atomic operations: read I; inc; write I, if multiple threads execute I ++ at the same time, volatile can only ensure that the I they operate on is the same memory, but dirty data may still be written. If you use the atomic wrapper classes added to Java 5, you do not need sychronized for operations such as increase.

The volatile keyword is believed to be clearly understood by readers who understand Java multithreading. The volatile keyword is used to declare simple type variables, such as int, float, and boolean data types. If these simple data types are declared as volatile, their operations will change to atomic level. But there are some restrictions. For example, n in the following example is not atomic:

Package mythread; public class JoinThread extends Thread {public static volatile int n = 0; public void run () {for (int I = 0; I <10; I ++) try {n = n + 1; sleep (3); // latency of 3 ms} catch (Exception e) {}} public static void main (String [] args) throws Exception {Thread threads [] = new Thread [100]; for (int I = 0; I <threads. length; I ++) // create 100 threads [I] = new JoinThread (); for (int I = 0; I <threads. length; I ++) // run the first thread threads [I] just created. start (); for (int I = 0; I <threads. length; I ++) // after all the 100 threads are executed, continue threads [I]. join (); System. out. println (n = + JoinThread. n );}}

If the operation on n is atomic, the final output result should be n = 1000. When the area code is executed, n is usually less than 1000, this indicates that n = n + 1 is not an atomic operation. The reason is that the simple variable declared as volatile does not work if the current value is related to the previous value of the variable, that is, the following expressions are not atomic operations:

N ++;
N = n + 1;

If you want to change this situation to an atomic operation, you need to use the synchronized keyword. The above code can be changed to the following form:

Package mythread; public class JoinThread extends Thread {public static int n = 0; public static synchronized void inc () {n ++;} public void run () {for (int I = 0; I <10; I ++) try {inc (); // n = n + 1 is changed to inc (); sleep (3 ); // to make the running results more random, the latency is 3 milliseconds} catch (Exception e) {}} public static void main (String [] args) throws Exception {Thread threads [] = new Thread [100]; for (int I = 0; I <threads. length; I ++) // create 100 threads [I] = new JoinThread (); for (int I = 0; I <threads. length; I ++) // run the first thread threads [I] just created. start (); for (int I = 0; I <threads. length; I ++) // after all the 100 threads are executed, continue threads [I]. join (); System. out. println (n = + JoinThread. n );}}

The code above changes n = n + 1 to inc (), where the inc method uses the synchronized keyword for method synchronization. Therefore, exercise caution when using the volatile keyword. Instead of modifying a simple type variable with volatile, all operations on this variable are original operations,When the value of a variable is determined by the previous one, such as n = n + 1 and n + + +, the volatile keyword is invalid, the operation on the variable is atomic level only when the value of the variable is irrelevant to the previous value, for example, n = m + 1. This is the original level.Therefore, be cautious when using volatile. If you are not sure about it, you can use synchronized instead of volatile.

1. Use volatile on the member variables accessed by two or more threads. You do not need to use this variable when it is already in the synchronized code block or a constant.
2. Because volatile is used to block the necessary code optimization in the VM, the efficiency is relatively low. Therefore, this keyword must be used when necessary.

 

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.