Dry: The volatile of Java Concurrent Programming series (i)

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:

The int a = 100 thread must now assign an operation to the cache of the variable i in its own worker thread, and then write to the host, instead of writing the value 100 directly into main memory.

Characteristics

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.

It is not guaranteed that the 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{publicvolatileintmnumber =0;publicstaticvoidmain (String []args) {        Final Hellovolatile Hello =newhellovolatile (); for (Inti =0, i<10; i++) {newthread () {Publicvoidrun () {for (INTJ = 0; j<1000; J + +) {                        Hello.mnumber ++;    &N Bsp              }               }    & nbsp      }.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

Publicclassdclsingleton{privatevolatilestaticdclsingleton minstance =null;publicstaticdclsingletongetinstance () {                 if (minstance==null) {synchronized (Dclsingleton.class) {if (minstance==null) {minstance =newdclsingleton ();    }}}returnminstance; }}

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.

End-of-text benefits:

Want to learn more about concurrent programming knowledge points, you can pay attention to me, I will also organize more about concurrent programming this piece of knowledge to share out, in addition, by the way to recommend an Exchange Learning Group:650385180, It will share some of the video footage recorded by a veteran architect: Spring,mybatis,netty source analysis, high concurrency, performance, distributed, microservices architecture, JVM performance optimization, and concurrent programming are the architects ' essential knowledge systems. can also receive free learning resources, currently benefiting a lot, the following learning resources are in the group's shared area.


Dry: The volatile of Java Concurrent Programming series (i)

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.