The principle underlying the volatile keyword

Reference book: "Java concurrent programming art" - the Xiaoming Fang Tengfei Wei Pengcheng

In concurrent programming, synchronized and volatile two keywords play an important role, volatile lightweight synchronized, it ensures the "visibility" of shared variables in a multiprocessor development.

So what is the "visibility" mean?

Visibility means that when a thread modifies a shared variable, another thread can read the value of this modified

If the volatile used properly, it will be lower than the cost of synchronized, because it does not cause obstruction threads, will not lead to context switching and scheduling, so better performance, lower cost.
 

volatile definitions

Java Language Specification Version 3 definition of volatile as follows:

Java programming language allows threads to access shared variables, in order to ensure shared variables can be accurately and consistently updated by thread should ensure exclusive lock to get this variable alone.

Java provides volatile, and in some cases to be more convenient than lock.

If a field is declared volatile, Java threading memory model (JMM) to ensure that all threads see the value of this variable is the same.

 

The principle volatile

Look at a simple example:

private volatile Singleton instance = null;

public Singleton getInstance(){
        if(instance == null){
            instance = new Singleton(); 
        }
        return instance;
}

instance of this member variable is modified volatile keyword, so for instance the reference is changed each thread is "visible." So volatile is how to ensure the visibility of it?

We get JIT compiler tool in x86 processors by generating assembly instruction to see when volatile write operation, CPU will do anything (is this code: instance = new Singleton();).

Converted into assembly code as follows:

0x01a3deld: movb $0x0,0x1104800(%esi);0x01a3de24: lock add1 $0x0,(%esp);

There volatile variable is modified when the shared variable write operation will be more of the second line of assembly code, Lock prefix instruction in multi-core processors will lead to two things:

  • The current data processor cache line is written back to system memory.
  • This memory will write back in the other CPU caches data in the memory address is not valid.

It is these two additional events such volatile to ensure the "visibility" of shared variables.

Guess you like

Origin blog.csdn.net/u013568373/article/details/94477266