Java Virtual machine memory model and volatile type variables

Source: Internet
Author: User

Java Virtual machine memory model

Understanding the memory model of a Java virtual machine can help us understand why thread-safety issues occur.

The above image is a < in-depth understanding of Java Virtual Machine-JVM advanced features and best practices > Books.

Thread-shared variables are stored in main memory (main memories).

A copy of a thread-shared variable is saved in the respective working memory of each thread (working memories).

The thread must be in working memory for all operations (reading, assignment, etc.) for a shared variable, and cannot read and write directly to the main memory variable.

The working memory of other threads is also inaccessible between different threads. The transfer of variables between threads needs to be done through main memory.

So the root of the thread safety problem is that when the shared variable is modified in main memory, the working memory of the thread is still the old value of the modified shared variable, which results in the result of inconsistent data.

Volatile type variable

Volatile modified variables are lightweight solutions to some of the thread safety issues, with 2 features:

1. Ensure that this variable is visible to all threads, meaning that when a thread modifies the value of the variable, the new value is immediately known to other threads.

However, it is not guaranteed that volatile can completely avoid the consistency of thread safety data.

Private volatile int race = 0; Private void Increase () {    race+ +;}

For example, the above code, if the multi-threaded call Increase () method, is not guaranteed to be thread-safe, and is very likely to occur data inconsistency problem.

The reason for this is that although volatile guarantees that changes to the race variable are immediately known to other threads, the line itself race++ the code is not an atomic operation. when the actual code is compiled, it becomes more than one bytecode.

Volatile usage scenarios are subject to 2 rules:

1) The result of the operation does not depend on the current value of the variable, or can ensure that only a single thread modifies the value of the variable;

2) variables do not need to participate in invariant constraints with other state variables.

The classic usage scenario for volatile variables is as follows. When the Dosomthing () method is called by multithreading, all the threads will not be in the next round while the shutdown=true is simply put.

Private volatile Boolean false ; Private void dosomething () {    while ( !  ShutDown) {        // do something    }}

2. Use volatile variables to prevent command reordering.

A normal variable will only guarantee that the correct result will be obtained in all places where the result of the assignment is dependent on the execution of the method, without guaranteeing that the order of the variable assignment is consistent with the order of execution in the program code. Because this cannot be perceived in the course of a county's method execution.

 Publicvolatileexample {Map configoptions; Char[] configtext; volatile Booleaninitiallized =false; Private voidinit () {configoptions=NewHashMap (); Configtext=Readonfigfile (fileName);        Processconfigoptions (Configtext, configoptions); Initialized=true; }    Private void  Do() {         while(!initialized)        {Sleep ();    } dosomethingwithconfig (); }}

The above code assumes that the Init () method and the Do () method run in a different thread. If the initialized variable is not using the volatile modifier, the init () method may be optimized for command reordering (instruction reordering is a machine-level optimization operation, Early execution means that the assembly code corresponding to this sentence will be executed in advance, resulting in the last code initialized=true being executed in advance. The consequence of this is the Do () method because initialized= True skips the while loop to execute Dosomethingwithconfig (), but it is possible that the Init () method has not yet run its end.

The volatile keyword avoids the occurrence of such situations.

Java Virtual machine memory model and volatile type variables

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.