The volatile of Java concurrency programming

Source: Internet
Author: User
Tags visibility volatile

The definition of volatile in the third edition of the Java Language specification is as follows: The Java programming language allows threads to access shared variables, and in order to ensure that shared variables can be updated accurately and consistently, the thread should ensure that the variable is obtained separately through an exclusive lock.

Before understanding the volatile keyword, you need to understand the following Java memory model, the Java memory model is abstracted as follows:

Java memory model

If you want to communicate between thread A and thread B, you must go through the following two steps (1) The updated shared variables in thread A and thread a local memory are flushed to memory. (2) thread B to main memory to read shared variables that were updated before thread A.

Thus the following statement is executed:

int a = 100Instead of writing the value 100 directly into main memory, the thread must now assign a value to the cache in which the variable I resides in its own worker thread, and then write to the main store.

Characteristics
    1. Visibility when a shared variable is modified by volatile, it guarantees that the modified value is immediately updated to main memory, so it is visible to other threads. When other threads need to read the value, other threads go to main memory to read the new value. In contrast, common shared variables do not guarantee visibility, because normal shared variables are not immediately written to main memory and are not determined when they are written to main memory. When other threads are reading this value, the main memory may still be the original old value, so that visibility is not guaranteed.

    2. The ordered Java memory model allows the compiler and processor to reorder instructions, although the reordering process does not affect the correctness of 单线程 execution, but it affects the correctness of multithreaded concurrency execution. This can be ensured by the volatile order, in addition to volatile, but also through the synchronized and lock to ensure the order of. Synchronized and lock ensure that only one thread executes synchronous code at a time, which is equivalent to having the thread sequentially execute synchronous code, guaranteeing order. Volatile is more lightweight and less expensive than synchronized and lock if atomic operations are not considered.

    3. The non-guaranteed atomic volatile keyword can only guarantee the visibility and ordering of shared variables. If volatile modifies a shared variable in a concurrent thread, and the shared variable is non-atomic, a problem occurs in concurrency. For example, the following code:

PublicClasshellovolatile{PublicVolatileint mnumber =0;PublicStaticvoidMainstring []args] {final Hellovolatile hello = new hellovolatile (); for (int i =0; I<10; i++) {new Thread () {public void run ( for (int J =0; J<1000; j + +) { Hello.mnumber + +; }}}.start (); } while (Thread.activecount () >2) {Thread.yield (); } System. out.println ( "number:" +hello.mnumber);}      

This code expects the result to be 10000, but each execution may be different. This is because either self-increment or decrement is non-atomic.

(1) If Mnumber is at this time equal to 100, thread 1 does the self-increment operation.

(2) Thread 1 reads the value of Mnumber 100 first, then it is blocked.

(3) At this time, thread 2 reads the value of Mnumber 100, and then the self-increment operation, and write to main memory, when the value in main memory is 101.

(4) Thread 1 continues to execute at this time because thread 1 has read the value 100 and then made a self-increment of 101 and then writes 101 to main memory.

You can see that two threads have performed +1 operations on 100, and the expected Nnumber = 102 in main memory, the actual MNUMEBR = 101; This is due to non-atomic operation.

Usage Scenarios

(1) In concurrent programming, it is not dependent on the state identification of any state in the program. You can use keyword volatile instead of synchronized to improve program execution efficiency and simplify your code.

(2) Double check mode of single case mode DCL

public  Class dclsingleton {private  Volatile static dclsingleton minstance = null; public static Dclsingleton getinstance () {if (mInstance==< Span class= "Hljs-keyword" >null) {synchronized (dclsingleton.class) {if (Minstance==null) {minstance = new Dclsingleton (); }}java Learning Group 669823128} return minstance;}        
Principle Analysis

Convert volatile-modified variables into assembly code, as follows:

... lock addl $0x0,(%rsp)

By checking the IA-32 architecture Security Manual, it is known that the lock prefix instruction will cause two things in the multi-core processor.

1) writes the data of the current processor cache row back to the system memory.

2) This write-back operation invalidates the data that is cached on the other CPU in the memory address.

Interpretation:

To improve, the processor does not communicate directly with the memory, but instead reads the system memory data into the internal cache before the operation, but does not know when to write back to memory. If you write to a variable that declares volatile, the JVM sends a lock prefix instruction to the processor, writing the data of the cache row where the variable resides to the system memory.

However, after memory is written, if the other processor caches a value that is still old, then performing the calculation will cause problems. Therefore, under multiprocessor, in order to ensure that each processor cache is consistent, the cache consistency protocol is implemented, such as:

Each processor checks to see if its cached data has expired by sniffing data propagated on the bus, and when the processor finds that the memory address of its cache line is modified, the cache line of the current processor is set to an invalid state. When the processor operates on this data, it will re-read the data from the system memory into the processor cache.

Java Learning Group 669823128

The volatile of Java concurrency programming

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.