Java Concurrency volatile keyword (tij21-21.3.3 21.3.4)

Source: Internet
Author: User

* * 1 Introduction
Volatile is a reserved keyword in Java, and its meaning in English is variable and unstable. Volatile, like final, static, and other modifiers, can modify a field in a class and not modify a local variable in a method. When you modify a field in a class, volatile can modify the Primative type or any object. This is shown in the following example:

public class Tij_volatile {
private volatile int i;
private volatile String s;
Private volatile object o = new Object ();
private volatile Object O2;
public static void Main (String ... args) {
volatile int i2 = 1;
}
}

The compiler will give an error alert on the line of the main method's volatile int i2 = 1.

* * 21 Examples to understand the difference between a volatile domain and a normal domain
So what is the difference between a variable declared volatile and a normal domain variable? In the literal sense, volatile variables are more unstable and more volatile than variables that are not declared volatile.
A typical example of a simple variable that requires different threads to read and write is a "stop request" flag bit that allows one thread to tell another thread to terminate, and in this case volatile is a good choice:

public class Stoppabletask extends Thread {
Private volatile Boolean pleasestop; The pleasestop variable is stored in the Java heap at the time of new Stoppabletask.
public void Run () {
while (!pleasestop) {
Do some stuff ...
}
}

public void Tellmetostop () {
Pleasestop = true;
}
}

In the example above, if the STOP request flag bit is not declared volatile and no other synchronization mechanism is used, then the stoppabletask thread reads the PLEASESTOP variable from the main memory. and cache it in its own line stacks (working memory) (in some articles, working memory is considered to be a virtual or abstract of the JVM's registers or caches of physical machines, so it reads and writes much faster than the main memory, reading data from working memory can improve read speed and optimize performance). In the back loop, the pleasestop will not be read again from the main memory, so the while loop will execute forever and the program fails. This is how non-volatile variables are read and written.

When declaring a variable as a volatile variable, it is tantamount to telling the compiler that the value of the variable is very variable, so you cannot optimize performance as a normal variable, and read it from the working memory without synchronizing with the main memory: because if it is not synchronized, the value of volatile is " Variable ", then the cached value in the working memory of the read may not be up to date, which could cause the execution of the program to fail! Because the cached value in the working memory of the volatile value can be synchronized with the most recent value of main memory, its value always looks like it is read directly from main memory and is always written directly to the main memory.

Believe that here, people should understand the meaning of volatile it? It is important to note that this semantics of volatile is not implemented completely correctly until Java 5. In previous versions of JVA5, volatile did not work properly. In Java5 and subsequent versions, reading a volatile variable looks like a direct manipulation of main memory: it makes copies of that variable in all cached threads working memory effectively synchronize with the variables in main memory. (volatile variables still have different copies in different threads).

* * 3 Java Memory model (JMM) and visibility

So what is main memory? What is working memory again? This inevitably involves the Java memory Model (Jmm,java). JMM will be devoted to an article in this blog, here we only need to look at the following this far-reaching JMM:

As can be seen in the JVM, each thread has its own working memory (working memories), the thread always backs up the variables in main memory, and stores it in its own working memory. Both the read and write of variables are performed in working memory (the Load/save process in the diagram). Normally, after the thread reads the variable from main memory for the first time, it assumes that the variable is relatively stable and immutable, so that when the thread later uses the variable, it assumes that the backup in its working memory is consistent with the variable in the primary, so it reads the backup directly from its working memory. The main purpose of this is to improve performance because reading data from memory is much slower than cache reads or even register reads.

The function of the volatile variable is to tell the thread: The variable is unstable and very easy to change, so every time you read a backup of that data in the working memory, it is re-load from the main memory. Note that doing so will degrade performance relative to normal variables. Here, in fact, the meaning of visibility has come out (the following paragraph from the network):

    Relative to memory, CPU speed is very high, if the CPU needs to access data directly with memory, during the access process, the CPU will be idle, this is a great waste, so the modern CPU has a lot of registers, multi-level cache, They have a much higher speed of access than memory. When a thread executes, a piece of data in memory exists in the working store of that thread (working memory, an abstraction of the cache and register, which is explained by the Concurrent programming in Java:design Principles and Patterns, Second Edition §2.2.7, Original: Every thread is defined to has a working memory (an abstraction of Cach ES and registers) in which to store values. A lot of people think that working memory is a part of the RAM, which may be translated into working memory for the sake of work, in order to avoid confusion, this is called the work store, each thread has its own working storage, and write back to memory at a particular time. Single thread, this is no problem, if it is multithreaded to access the same variable at the same time? A variable in memory exists in more than one work store, and thread 1 modifies the value of variable a when it is visible to thread 2. In addition, the compiler or runtime can reorder the instructions in order to be efficient, and the order of reordering is inconsistent with the code, so that thread 2 reads a variable and thread 1 may not have been written yet, although the code sequence is preceded by a write operation.

According to the above description, it is not difficult to see that the visibility is actually refers to a thread of the main memory of the changes in the data, is not visible to other threads.

* * The difference between 4 and synchronization lock mechanism

The volatile keyword provides only part of the synchronization functionality provided by synchronization, which means that volatile guarantees the visibility of all threads in the main memory, or provides the ability to synchronize between the main memory and the working memory. However, the use of volatile is relatively low relative to the wide application of the SYNCHRONIZED keyword in Java server-side programming, because it does not solve any synchronization problems that can be resolved by the Synchronized keyword.

As can be seen from the following example, volatile does not guarantee the synchronization of threads that write variables at the same time:

public class Counter {
public volatile static int count = 0;
public static Void Inc () {
The delay is 1 milliseconds, making the result obvious
try {
Thread.Sleep (1);
} catch (Interruptedexception e) {
}
count++; In Java, it is not an atomic operation. You can use Atomicinteger to guarantee atomicity.
}
public static void Main (string[] args) {
Start 1000 threads at the same time to perform i++ calculations to see the actual results
for (int i = 0; i <; i++) {
New Thread (New Runnable () {
@Override
public void Run () {
Counter.inc ();
}
}). Start ();
}
There may be different values for each run, which may be 1000
SYSTEM.OUT.PRINTLN ("Running result: counter.count=" + counter.count);
}
}

The above program in the multi-threaded environment, most of the time will fail. The reason for this is that the volatile modifier is used for the count variable in the program, which ensures that when different threads read the value of Count (read in working memory), the count value is consistent with the value in main memory. However, this consistency does not guarantee that when two threads execute count++ at the same time, the value of count is incremented only once. Why this happens because in Java, the count++ operation is not atomic (note that count++ is atomic in C + +). count++ is essentially a composite of the following atomic operations: reads (load) The value of count from main memory to the working memory of the thread, performs a count++ operation on a copy of count in working memory, writes the Count value (updated) in the working memory to (save) to main memory.

When two threads perform the count++ operation at the same time, the following conditions may occur:

Assuming that the current value of count in main memory is 0, thread 1 reads the value into working memory (0), at which point the thread scheduling mechanism interrupts the thread 1,thread 2 starts executing and reads the value into its working memory (0), at which point the thread scheduling mechanism interrupts the thread again 2,thread1 re-executes and performs the count++ operation (for the count copy in working memory), at which point the count value in the working memory is still 0, even though the count is re-synchronized from main memory, the value of the number of work in the count++ The operation is 1. At this point, the thread scheduling mechanism interrupts thread1,thread2 again and performs the count++ operation because at this point the count value in Thread1 working memory (1) is not save to main memory. So the count copy in Thread2 working memory is updated to 1 after performing the count++ operation.

In subsequent program execution, regardless of the order in which the Thread1 thread2 is executed, the count value in the final main memory is 1, and the program execution fails.

In order for the program to execute correctly, there are two ways to modify it, the first is to use the built-in lock with the Synchronized keyword (or use an explicit lock with the lock object), and the second method is to use the atomic Atom class introduced in Java5. (Atomic classes are described later in this article).


* * 5 atomicity and Atomic class
In the example in the previous section, the concept of atomicity has been involved. Atomicity guarantees that the operation will not be interrupted by the thread scheduling mechanism until it is completed. That is, an atomic operation is a guarantee that the operation will not be interrupted by the thread-scheduling mechanism until it is complete. It is important to note that atomicity does not guarantee the correctness of concurrent programs:

public class Tij_21_3_3_atomicitytest implements Runnable {

private int i = 0;

public int GetValue () {return i;}

Private synchronized void Evenincrement () {i++; i++;}//Evenincrement is not atomic and can be interrupted by thread scheduling mechanism

public void Run () {

while (true) evenincrement ();

}

public static void Main (string[] args) {

Executorservice exec = Executors.newcachedthreadpool ();

Tij_21_3_3_atomicitytest at = new Tij_21_3_3_atomicitytest ();

Exec.execute (at);

while (true) {

int val = At.getvalue ();

if (val% 2 = 0) {

System.out.println (Val);

System.exit (0);

}

}

}

}/* Output: (Sample)

191583767

*///:~

In the example above, although the operation in the GetValue () method is atomic, this does not guarantee the correctness of the program. The apparent atomicity and the right concurrency are two completely different concepts.

Atomic introduction is over, so what is the atomic class? Here's a look: the concept of atomic classes was introduced in Java SE5. Typical atomic classes include: Atomiclnteger, Atomiclong, Atomicreference, et. They provide atomic conditional update operations in the following form: Boolean Compareandset (Expectedvalue, Updatevalue); and the Atomic modification operation:

int addandset (int delta). Look at the following example:


: Concurrency/atomicintegertest.java
Import java.util.concurrent.*;
Import java.util.concurrent.atomic.*;
Import java.util.*;

public class Atomicintegertest implements Runnable {
Private Atomicinteger i = new Atomicinteger (0);
public int GetValue () {return i.get ();}
private void Evenincrement () {i.addandget (2);}//Atomic operation cannot be interrupted
public void Run () {
while (true)
Evenincrement ();
}
public static void Main (string[] args) {
New Timer (). Schedule (new TimerTask () {
public void Run () {
System.err.println ("aborting");
system.exit (0);
}
}, 5000); Terminate after 5 seconds
Executorservice exec = Executors.newcachedthreadpool ();
Atomicintegertest ait = new Atomicintegertest ();
Exec.execute (AIT);
while (true) {
int val = Ait.getvalue ();
if (val% 2 = 0) {
System.out.println (Val);
System.exit (0);
}
}

}
} ///:~

In the example above, we use Atomicinteger instead of the Synchronized keyword. It should be emphasized, however, that atomic classes are designed to implement classes in Java.util.concurrent, and only in a few cases need to be used in their own code. It is generally more secure to use locks directly (synchronize or explicit lock objects).


* * 6 Summary: When to use volatile?

Volatile variables have the ability to read and write the synchronization of an object, especially the memory synchronization feature. Volatile does not necessarily and cannot modify the final variable, because the final variable is immutable, and the meaning of volatile is variable. You should use a lock mechanism (synchronization or explicit lock) instead of volatile when you perform some complex operations on variables and you want to prevent other threads from accessing those variables while you do them.
Typical scenario for using volatile: Modify a variable in one thread as a flag, check the flag variable in another thread, and most importantly, the new value to write does not depend on the current value. The above-mentioned principles make it inappropriate to use the volatile keyword for operations such as X + + or × + = 7, because such operations are not atomic in Java (Atomic in C + +), but instead contain a series of operations that read the current value, increase it, and then write a new value. A common misconception is that X + + is atomic in Java. If you need this atomicity, you need Atomicinteger or similar other classes.

The following example uses volatile and synchronized to achieve "less expensive read-write locks":
public class Cheesycounter {
private volatile int value;
public int GetValue () {return value;}
public synchronized int increment () {
return value++;
}
}

The

    increment function is synchronous, so it cannot be executed concurrently, which guarantees the correctness of the multi-threaded write operation. At the same time as a write operation, multiple threads can read the value variable concurrently, and the values read by different threads at the same moment are guaranteed to be consistent and can be executed concurrently with the write operation.  

Finally, leave a question: Is it like Java's readlock% Writelock? How is Java's read-write lock implemented?

Reference documents:

Http://www.cnblogs.com/aigongsi/archive/2012/04/01/2429166.html
Http://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.html
Http://www.ibm.com/developerworks/cn/java/j-jtp06197.html
Http://stackoverflow.com/questions/16719004/should-i-use-volatile-if-i-use-synchronized
Happens-before Vulgar Solution Http://ifeve.com/easy-happens-before/
Http://javamex.com/tutorials/synchronization_volatile_typical_use.shtml
Http://javamex.com/tutorials/synchronization_concurrency_7_atomic_updaters.shtml
Http://javamex.com/tutorials/synchronization_concurrency_7_atomic.shtml
Http://javamex.com/tutorials/synchronization_concurrency_7_atomic_updaters.shtml
Http://javamex.com/tutorials/synchronization_volatile_dangers.shtml

Java Concurrency volatile keyword (tij21-21.3.3 21.3.4)

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.