Java Volatile Keyword FAQ

Source: Internet
Author: User
Tags visibility

volatile features

Memory visibility: In layman's terms, thread A's modification of a volatile variable is visible to other threads, that is, the value of each time a thread gets a volatile variable is up-to-date.

volatile The usage scenario

Keyword Sychronize prevents multiple threads from entering the same piece of code, and in some specific scenarios, volatile is equivalent to a lightweight sychronize,

Because the context switch of the thread is not caused, the use of volatile must satisfy two conditions:
1, the write operation of the variable does not rely on the current value, such as the execution of a++ under multi-threading, is unable to guarantee the accuracy of the result of volatile;
2, the variable is not included in the invariant with other variables, this sentence is a bit awkward, see the code is more intuitive.

 Public classNumberrange {Private volatile intLower =0; Private volatile intUpper =Ten;  Public intGetlower () {returnLower;}  Public intGetupper () {returnUpper;}  Public voidSetlower (intvalue) {         if(Value >Upper)Throw Newillegalargumentexception (...); Lower=value; }     Public voidSetupper (intvalue) {         if(Value <Lower)Throw Newillegalargumentexception (...); Upper=value; }}

In the above code, the upper and lower bounds are initialized to 0 and 10, respectively, assuming that threads A and B perform both setlower (8) and Setupper (5) At some point, and both pass invariant checks.

Set an invalid range (8, 5), so in this scenario, you need to guarantee the method through Sychronize Setlower and setupper only one thread can execute at a time.

Here are two scenarios in which we often use the volatile keyword in our projects:

1. Status Mark Amount
In a high concurrency scenario, how do you control whether code goes through promotional logic through a boolean-type variable isopen?

 Public classServerhandler {Private volatileIsOpen;  Public voidrun () {if(isopen) {//Promotion Logic}Else {          //Normal Logic        }    }     Public voidSetisopen (Boolean isopen) { This. isopen =IsOpen}}

Scene details need not be overly tangled, here is just an example of how volatile is used, the user's request thread to execute the Run method, if you need to open a promotion,

Can be set through the background, the implementation can send a request, call the Setisopen method and set IsOpen to True, because isopen is volatile decorated,

So once modified, the other threads can get the newest value of isopen, the user request can execute the promotion logic.

2.double check
One implementation of the Singleton mode, but many people will ignore the volatile keyword, because without the keyword, the program can also run very well,

Only the stability of the code is not 100%, perhaps in the future some time, hidden bugs will come out.

classSingleton {Private volatile StaticSingleton instance;  Public StaticSingleton getinstance () {if(Instance = =NULL) {syschronized (Singleton.class) {                if(Instance = =NULL) {instance=NewSingleton (); }            }        }        returninstance; } }

However, in the implementation of a large number of singleton patterns, I would recommend lazy loading elegant notation initialization on Demand Holder (Iodh).

 Public class Singleton {      staticclass  singletonholder {          staticnew Singleton ();      }        Public Static Singleton getinstance () {          return  singletonholder.instance;      }  }

Of course, direct initialization works better if you don't need lazy loading.

How to ensure memory visibility?

In the memory model of the Java Virtual machine, there is the concept of main memory and working memory, and each thread corresponds to a working memory,

And share the main memory data, let's see what the difference is between manipulating the normal variable and the volatile variable:

1, for ordinary variables: read operation will first read the working memory data, if not in the working memory, then copy a copy of the data from the main memory into the working memory;

The write operation modifies only the copy data of the working memory, in which case the other thread cannot read the latest value of the variable.

2, for volatile variables, read operation JMM will be the corresponding value in the working memory is invalid, require the thread to read the data from the main memory;

When writing, JMM flushes the corresponding data in the working memory into main memory, in which case other threads can read the latest value of the variable.

The memory visibility of volatile variables is based on memory Barrier, what is a memory barrier? A memory barrier, also known as a memory fence, is a CPU instruction.

In order to improve execution performance when the program is running, the compiler and the processor reorder the instructions, JMM to ensure the same results on different compilers and CPUs.

Suppresses specific types of compiler reordering and handler reordering by inserting a specific type of memory barrier.

Inserting a memory barrier tells the compiler and the CPU: No instructions can be reordered with this memory barrier instruction.

This text seems a little pale, rather than a concise code:

classSingleton {Private volatile StaticSingleton instance; Private intA; Private intb; Private intb;  Public StaticSingleton getinstance () {if(Instance = =NULL) {syschronized (Singleton.class) {                if(Instance = =NULL) {a=1;//1b =2;//2Instance =NewSingleton ();//3c = a + B;//4                }            }        }        returninstance; } }

1, if the variable instance no volatile modification, statements 1, 2, 3 can be arbitrarily reordered execution, that is, the instruction execution process may be 3214 or 1324.
2, if the volatile modified variable instance, will be inserted in the front and back of statement 3 a memory barrier.

By observing the assembly code generated by the volatile variable and the normal variable, it can be found that the operation of the volatile variable will have a lock prefix directive:

Java code:

Instance = new Singleton ();

Assembly Code:

0x01a3de1d:movb $0x0,0x1104800 (%esi);

0x01a3de24: **lock** addl $0x0, (%ESP);

This lock prefix instruction corresponds to the above memory barrier and provides the following guarantees:
1. Write the data of the current CPU cache line back to main memory;
2. This write-back operation results in an invalid data cache for the memory address on the other CPU.

In order to improve processing performance, the CPU does not directly communicate with the memory, but instead reads the memory data into the internal cache (L1,L2), but the operation is not determined when it is written back to memory, if the volatile variable is written, when the CPU executes to the lock prefix instruction, Will write the data of the cache row of this variable to memory, but there is still a problem, even if the memory data is up-to-date, the other CPU cache or the old value, so in order to ensure the cache consistency of each CPU, each CPU by sniffing the data propagated on the bus to check their cached data validity, When the data of the memory address corresponding to the cache row is found to be modified, the cache row is set to an invalid state, and when the CPU reads the variable, the cache row is set to invalid and the data is re-read from memory to the cache.

Reprinted from: Book of Little Wolf Http://www.jianshu.com/p/195ae7c77afe

Java Volatile Keyword FAQ

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.