Java Concurrency keyword volatile

Source: Internet
Author: User

Java Concurrency keyword volatile

@author Ixenos

Volatile only guarantees the visibility of shared variables and does not guarantee the atomicity of synchronous operations

Synchronization block and volatile keyword mechanism

Synchronized
Synchronization block Everyone is more familiar with, through the Synchronized keyword to achieve, all plus synchronized and block statements, in multi-threaded access, at the same time only one thread can use synchronized modified method or block of code.

Volatile
With volatile modifiers, the thread reads a copy of the most recent value modified by the variable to the line stacks each time a variable is used. Volatile can easily be mistakenly used for atomic operations, because the thread operates on its copy only, and does not change the value of variables in shared memory in real time.

Why do VMS use replicas, which can perform read-write reordering optimizations when operating on replicas, which can improve operational efficiency, rather than using volatile to suppress the use of replicas, and restrict reordering operations around volatile variables, Detailed analysis see: In-depth understanding of Java memory Model (iv)--volatile

Here is an example, we implement a counter, each time the thread starts, the Counter Inc method is called, the counter is added a

1  Public classCounter {2 3      Public Static intCount = 0; 4 5      Public Static voidInc () {6 7         //The delay is 1 milliseconds, making the result obvious8         Try { 9Thread.Sleep (1); Ten}Catch(interruptedexception e) { One         }  A  -count++;  -     }  the  -      Public Static voidMain (string[] args) { -  -         //Start 1000 threads at the same time to perform i++ calculations to see the actual results +  -          for(inti = 0; i < 1000; i++) {  +             NewThread (NewRunnable () { A @Override at                  Public voidrun () { - counter.inc (); -                 }  - }). Start ();  -         }  -  in         //there may be different values for each run, which may be -SYSTEM.OUT.PRINTLN ("Run Result: counter.count=" +counter.count);  to     }  + } -  the /*running Result: counter.count=995*/ 

The results of the actual operation may be different each time, the result of this machine is: Running result: counter.count=995, you can see, in the Multi-threaded environment, Counter.count did not expect the result is 1000

Many people think that this is a multi-threaded concurrency problem, just need to add the variable count before the volatile can avoid this problem, then we change the code to see if the result is not in line with our expectations

1  Public classCounter {2 3      Public volatile Static intCount = 0; 4 5      Public Static voidInc () {6 7         //The delay is 1 milliseconds, making the result obvious8         Try { 9Thread.Sleep (1); Ten}Catch(interruptedexception e) { One         }  A  -count++;  -     }  the  -      Public Static voidMain (string[] args) { -  -         //Start 1000 threads at the same time to perform i++ calculations to see the actual results +  -          for(inti = 0; i < 1000; i++) {  +             NewThread (NewRunnable () { A @Override at                  Public voidrun () { - counter.inc (); -                 }  - }). Start ();  -         }  -  in         //there may be different values for each run, which may be -SYSTEM.OUT.PRINTLN ("Run Result: counter.count=" +counter.count);  to     }  + } -  the /*running Result: counter.count=992*/ 

The results of the operation is still not what we expected 1000, let us analyze the reasons below

In the Java garbage collection article, the allocation of memory at runtime of the JVM is described. One of the memory areas is the JVM virtual machine stack, each thread runs with a line stacks, and the line stacks saves the thread runtime variable value information . When a thread accesses an object, the value of the variable that corresponds to the heap memory is found first through the object's reference, then the concrete value of the heap memory variable is load into the thread's local memory, a copy of the variable is created, and then the thread is no longer related to the object's value in the heap memory variable. , instead of directly modifying the value of the replica variable , the value of the thread variable copy is automatically written back to the object's variable in the heap at some point after the modification (the thread exits). This changes the value of the object in the heap.

The following picture depicts this write interaction:

Read and load copy variables from main memory to current working RAM
Use and assign execute code, change shared variable value
Store and write refresh main memory related content with work-in-RAM data

Where use and assign can appear multiple times

However, these operations are not atomic , that is, after the read load, if the main memory count variable is modified, the value in the thread's working memory will not change because it has already been loaded, so the computed result will be different from what is expected.

In summary, volatile enables threads to interact directly with shared memory data and prevent the reordering of VMS from being optimized

For volatile-modified variables, the JVM virtual machine simply guarantees that the value from main memory load to the working memory of the thread is up-to-date

Java concurrency keyword volatile

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.