In Java thread concurrency processing, there is a great deal of confusion about the use of a keyword volatile, thinking that by using this keyword, you can do everything in parallel with multithreading. The Java language supports multithreading, in order to solve the problem of thread concurrency, the synchronization block and volatile keyword mechanism are introduced into the language. Synchronized synchronized block Everyone is more familiar with the Synchronized keyword to achieve, all add synchronized and block statements, in multi-threaded access, at the same time only one thread can be modified by the Synchronized method or code block. Volatile a variable that is decorated with volatile, the thread reads the variable's most-modified value every time it uses the variable. Volatile are easily misused for atomic manipulation. Let's look at an example where we implement a counter that invokes the Counter Inc method each time the thread starts, adding an execution environment to the counter--JDK version: jdk1.6.0_31, Memory: 3G cpu:x86 2.4G Copy code code as follows: public class Counter {public static int count = 0; the public static Void Inc () {//) is delayed 1 milliseconds, resulting in a significant try {Thread.Sleep (1);} catch (Interru Ptedexception e) {} count++; public static void Main (string[] args) {//Start 1000 threads at the same time to perform i++ calculations to see the actual result for (int i = 0; i < 1000; i++) {New Thread (NE W Runnable () {@Override public void run () {counter.inc ();}}). Start (); }//The value of each run here may be different, may be 1000 System.out.println ("Run Result: counter.count=" + counter.count); Run results: counter.count=995 The actual results of the operation may be different each time, the results of this machine: the results of the operation: counter.count=995, you can see that in a multi-threaded environment, Counter.count did not expect the result is 1000 Many people think that this is a multithreaded concurrency problem,Just add volatile to the variable count before you can avoid the problem, so we're going to look at the code and see if the result is the same as we expected. Copy code code as follows: public class Counter {public volatile static int Count = 0; public static Void Inc () {//Is delayed 1 milliseconds, resulting in a significant try {Thread.Sleep (1);} catch (Interruptedexception e) {} count++;} public static void Main (string[] args) {//Start 1000 threads at the same time to perform i++ calculations to see the actual result for (int i = 0; i < 1000; i++) {New Thread (new RUNNABL E () {@Override public void run () {counter.inc ();}}). Start (); }//The value of each run here may be different, may be 1000 System.out.println ("Run Result: counter.count=" + counter.count); Run results: counter.count=992 The results are still not 1000 of what we expected, so let's analyze why. In the Java garbage collection article, we describe the allocation of memory at the time of the JVM runtime. One of the memory areas is the JVM virtual machine stack, each thread running with a line stacks, the line stacks saved the thread run-time variable value information. When a thread accesses a value for an object, first, the value of the variable in the heap memory is found by the reference of the object, then the concrete value of the heap memory variable is load into the thread local memory, a copy of the variable is established, and then the thread no longer has any relationship with the object in the heap memory variable value, but modifies the copy variable At some point after the modification (before the thread exits), the value of the thread variable copy is automatically written back to the object's variable in the heap. This makes the value of the object in the heap change. The following diagram depicts this write interaction Java volatile1read and load copying variables from main memory to the current working memory use and assign executing code, changing shared variable values store and write uses working memory data to refresh main memory related content. Assign can appear multiple times but these operations are not atomic, that is, after read load, such asAfter the main memory count variable has been modified, the value in the thread's working memory is not changed because it has already been loaded, so the calculated results will be different from what is expected for volatile-modified variables. The JVM virtual machine only guarantees that the values loaded from the main memory to the working memory of the thread are up to date, for example, if thread 1, thread 2, in the read,load operation, discovers that the value of count in main memory is 5, then the latest value is loaded thread 1 heap count is modified, Writes to main memory, and the count variable in main memory becomes 6 thread 2 because the read,load operation has already been performed, the variable value of the main memory count is updated after the operation, which causes two threads to be modified with the volatile keyword in a timely manner. There will still be concurrent situations. You may be interested in articles: What does the volatile keyword in Java mean? Java Concurrent Programming: Volatile keyword detailed analysis of the function and usage of volatile keyword in Java discussion on the understanding of the volatile keyword in Java java in the volatile keyword detailed Java thread programming in the V The role of Olatile keywords Java multithreaded programming prudence use the meaning of the volatile keyword Java volatile keyword in detail
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.