Java Concurrency Programming and volatile

Source: Internet
Author: User

http://www.importnew.com/24082.html volatile keyword

Principle Analysis of http://www.importnew.com/16142.html Concurrenthashmap

Java Memory Model:

In the Java memory model, memory is divided into two categories, the main memory and working memory,main memory for all threads to share, working memory is stored in the thread is required to copy the variables (the thread to the main Memory of the contents of the operation, the first need to copy to their own working memory, generally for speed, working memory is generally in the CPU cache). Volatile variables do not produce a copy of the working memory when manipulated, but instead directly manipulate the main memory, although volatile solves the problem of variable visibility, but does not solve the atomic problem of variable operation, This also requires synchronized or CAS-related operations.

The Java memory model specifies that all variables are stored in main memory. Each thread also has its own working memory, and the thread's working memory holds the variables used by the thread (the variables are copied from the main memory). All operations of a thread on a variable (read, assign) must be in working memory. There is no direct access to variables in the other's working memory between different threads, and the transfer of variable values between threads needs to be done through main memory.

Three concepts of concurrent programming: atomicity, ordering, visibility.

Visibility of

It is also said that if an object has a variable i, then i is stored in the main memory, when a thread to operate I, the first need to load I from the main memory in the working memory of this thread, this time working There is a copy of I in memory, this time the thread modifies I in its working memory until it writes I from working memory to the main memory, and the new I value can be read by other threads. In a sense, visibility guarantees the consistency of the working memory data for each thread. Visibility follows some of the following rules:

    • When a thread finishes running, all the written variables are flush back to the main memory.
    • When a thread reads a variable for the first time, it reads the latest from the main memory.
    • Volatile variables are immediately written to the main memory, and in jsr133, the semantics of volatile are enhanced, which is mentioned later
    • When a thread releases a lock, all changes to the variable are flush into main memory, and then a process that uses the same synchronization lock will reload all the variables used, thus guaranteeing visibility.
Atomic Nature

Also with the above example, Atomicity is when a thread modifies the value of I, from removing I to the value of the new I to I no other thread can do anything to I. This means that the operation of a thread on I is atomic, so that the data can be prevented from being dirty read. Operations can be guaranteed by locking mechanisms or CAS (Compare and Set require hardware CPU support).

Order of

Assume that there are two variables I and J in main memory, the initial value is 0, in the code of a thread A in turn I and J for the self-increment operation (I,j operation does not depend on each other)

12 i++;j++;

Because of this, the order of the I,J modification operations may be reordered. Then the modified IJ write to the main memory, the order may not be in accordance with the order of I,j, this is called reordering, in a single-threaded case, when thread a runs the end of the value of I,j added 1, The thread itself looks as if the threads are running in the order of the code (these operations are based on as-if-serial semantics), and even in the actual run, the i,j's self-increment may be reordered, and of course the computer can't help you sort them out. There must be no change in the order in which the upper and lower logical associations are run. But in a multithreaded environment, the problem is different, such as the code of another thread B is as follows

123 if(j==1) {    System.out.println(i);}

According to our way of thinking, when J is 1, then I must also be 1, because the code i before J is self-increment, but the actual situation is possible when J is 1 I or 0. This is the bad consequence of reordering, so we sometimes need some necessary strategies to avoid such problems, in order to ensure that multiple threads work together in a certain sequence. JMM provides a sorting strategy for Happens-before. So we can get the as-if-serial semantics in the multi-threading environment. Here does not have the detailed explanation to Happens-before, in detail please look here http://www.ibm.com/developerworks/cn/java/j-jtp03304/, This is mainly about the changes in volatile under the new Java memory model, and the following code may be problematic before jsr133

123456789101112 Map configOptions;char[] configText;volatile boolean initialized = false;// In Thread AconfigOptions = new HashMap();configText = readConfigFile(fileName);processConfigOptions(configText, configOptions);initialized = true;// In Thread Bwhile (!initialized)   sleep();// use configOptions

Before jsr133, although the read and write of volatile variables cannot be reordered with read and write to other volatile variables, they can still be reordered with reads and writes to the nonvolatile variable, so the above thread a operation, It is possible that the initialized becomes true, and ConfigOptions has not been initialized, so initialized before ConfigOptions is seen by thread B, it creates a problem.

The JSR 133 Expert Group decided that volatile read and write could not be reordered with other memory operations, and in the new memory model, if thread a writes to the volatile variable V and thread B reads V, then when writing V, all of the variable values visible to a can now be To ensure that the B is visible.

The result is more volatile semantics, at the expense of having a greater impact on performance when accessing volatile fields. This is used in the count variable that counts the number of segment elements in Concurrenthashmap.

Deep understanding of volatile keyword 1.volatile guaranteed visibility

Once a shared variable (a member variable of a class, a static member variable of a class) is modified by volatile, then there are two layers of semantics:

1) ensures the visibility of different threads operating on this variable, that is, one thread modifies the value of a variable, which is immediately visible to other threads.

2) command reordering is prohibited.

Look at a piece of code first, if thread 1 executes first, thread 2 executes:

12345678 //线程1booleanstop = false;while(!stop){    doSomething();}//线程2stop = true;

This code is a typical piece of code, and many people may use this notation when they break a thread. But in fact, is this code going to work exactly right? Is it bound to break the thread? Not necessarily, perhaps most of the time, this code can break the thread, but it can also lead to the inability to break threads (although this is a very small possibility, but as soon as this happens it will cause a dead loop).

The following explains why this code may cause the thread to fail. As explained earlier, each thread has its own working memory as it runs, and when thread 1 runs, it copies a copy of the value of the stop variable into its working memory.

Then when thread 2 changed the value of the stop variable, but before it could write to the main memory, thread 2 went to do something else, and thread 1 would have been looping because it did not know that thread 2 had changed the stop variable.

But it becomes different after the volatile modification:

First: Using the volatile keyword forces the modified value to be immediately written to main memory;

Second: With the volatile keyword, when thread 2 is modified, it causes thread 1 to work in-memory cache variable stop cache row is invalid (reflected to the hardware layer, the CPU L1 or the corresponding cache line in the L2 cache is invalid);

Third: Because thread 1 works in-memory cache variable stop cache line is invalid, so thread 1 reads the value of the variable stop again to read the main memory.

Then thread 2 when modifying the stop value (of course, this includes 2 operations, modify the value in the thread 2 working memory, and then write the modified value to memory), will make thread 1 in the work in-memory cache variable stop cache row is invalid, and then threads 1 read, found that their cache row is invalid, It waits for the cache line corresponding to the main memory address to be updated, and then goes to the corresponding main memory to read the latest value.

Then thread 1 reads the latest correct value.

2.volatile does not guarantee atomicity

Let's look at an example:

1234567891011121314151617181920212223 public class Test {    public volatile int inc = 0;    public void increase() {        inc++;    }    public static void main(String[] args) {        final Test test = new Test();        for(int i=0;i<10;i++){            new Thread(){                public void run() {                    for(int j=0;j<1000;j++)                        test.increase();                };            }.start();        }         while(Thread.activeCount()>1)  //保证前面的线程都执行完            Thread.yield();        System.out.println(test.inc);    }}

How much do you think the output of this program is? Maybe some friends think it's 10000. But in fact running it will find that each run results in an inconsistent, a number less than 10000.

Maybe some friends will have doubts, no Ah, the above is the variable Inc self-increment operation, because volatile guarantees the visibility, then in each thread after the INC self-increment, in other threads can see the modified value ah, so there are 10 threads have 1000 operations respectively, Then the value of the final Inc should be 1000*10=10000.

There is a misunderstanding here, the volatile keyword can ensure that the visibility is not wrong, but the above procedure is not able to guarantee the atomic nature. Visibility only guarantees the most recent value per read, but volatile has no way of guaranteeing the atomicity of the operation of the variable.

As mentioned earlier, the self-increment operation is not atomic, it includes reading the original value of the variable, adding 1 operations, writing to the working memory. That is, the three sub-operations of the self-increment operation may be split and executed, which may cause the following to occur:

If the value of the variable Inc is 10 at a time,

Thread 1 self-increment the variable, thread 1 reads the original value of the variable Inc first, and then thread 1 is blocked;

Thread 2 then self-increment the variable, and thread 2 also reads the original value of the variable inc, since thread 1 is only reading from the variable Inc, without modifying the variable, so it does not invalidate the cache line of the working in-memory cache variable inc of Thread 2, nor does it cause the value in main storage to refresh. So thread 2 will go directly to main memory to read the value of INC, find the value of INC 10, and then add 1 operations, and 11 write to the working memory, and finally write to main storage.

Then thread 1 then adds 1, since the value of the INC has been read, note that at this point the value of the in-Memory inc of Thread 1 is still 10, so that Threads 1 to Inc 1, and then 11 to the working memory, and finally to main storage.

Then, after two threads had a single self-increment operation, Inc increased by 1.

The source is here, the self-increment operation is not atomic, and volatile does not guarantee that any operation on the variable is atomic.

Solution: You can use synchronized or lock to lock, to ensure the atomicity of the operation. You can also pass Atomicinteger.

Some atomic operation classes are provided under the Java 1.5 java.util.concurrent.atomic package, namely, the self-increment of the base data type (plus 1 operations), the decrement (minus 1 operations), and the addition operation (plus one number), the subtraction operation (minus one number) is encapsulated, Ensure that these operations are atomic operations. Atomic is the use of CAs to achieve atomic operations (Compare and Swap), the CAs are actually implemented using the CMPXCHG instructions provided by the processor, and the processor execution CMPXCHG instruction is an atomic operation.

3.volatile Guaranteed Order

It is mentioned that the volatile keyword can prohibit order reordering, so volatile can be guaranteed to a certain degree of order.

The volatile keyword prohibit command reordering has two layers of meaning:

1) When the program performs a read or write operation to a volatile variable, the changes in its preceding operation must have been made, and the result is already visible to the subsequent operation;

2) When the instruction is optimized, it is not possible to put a read or write statement on a volatile variable behind it, or to put the statement behind the volatile variable before it executes.

Maybe it's more about the above, for a simple example:

12345678 //x、y为非volatile变量//flag为volatile变量x = 2;        //语句1y = 0;        //语句2flag = true;  //语句3x = 4;         //语句4y = -1;       //语句5

Because the flag variable is a volatile variable, then in the process of order reordering, the statement 3 will not be placed in statement 1, Statement 2 before the statement 3 is not put into statement 4, statement 5 after. Note, however, that the order of statement 1 and Statement 2, Statement 4, and statement 5 are not guaranteed.

And the volatile keyword guarantees that execution to the statement 3 o'clock, Statement 1 and statement 2 must be completed, and statement 1 and statement 2 execution results to statement 3, Statement 4, Statement 5 is visible.

So let's go back to one of the examples above:

123456789 //线程1:context = loadContext();   //语句1inited = true;             //语句2//线程2:while(!inited ){  sleep()}doSomethingwithconfig(context);

In the preceding example, it is mentioned that it is possible that statement 2 will be executed before statement 1, so long may cause the context to not be initialized, and thread 2 will use the uninitialized context to operate, resulting in a program error.

If the inited variable is decorated with the volatile keyword, this problem does not occur because the context is guaranteed to be initialized when executing to statement 2 o'clock.

Principle of implementation of volatile 1. Visibility

In order to improve processing speed, not directly with the memory to communicate, but the system memory of the data unique internal cache before the operation, but after the operation is not known when the memory will be written.

If a write is declared for a volatile variable, the JVM sends a lock prefix instruction to the processor that writes the data of the cache row where the variable resides to the system memory. This step ensures that the main in-memory data is updated immediately if other threads modify the declared volatile variable.

But at this time the cache of other processors is still old, so in a multiprocessor environment, in order to ensure that each processor cache consistent, each processing by sniffing the data propagated on the bus to check whether their cache expires, when the processor found its own cache line corresponding memory address has been modified, The cache line of the current processor is set to an invalid state, and when the processor modifies the data, it forces re-reading the data from the system memory into the processor cache. This step ensures that other threads get the declaration that the volatile variable is up-to-date from main memory.

2. Order

The lock prefix instruction is actually equivalent to a memory barrier (also known as a Memory fence), which ensures that the instruction is reordered without putting the instructions behind it into place before the memory barrier, and does not queue the preceding instruction behind the memory barrier, that is, the operation in front of the memory barrier is fully completed.

Application Scenarios for volatile

The Synchronized keyword is to prevent multiple threads from executing a piece of code at the same time, which can affect program execution efficiency, while the volatile keyword has better performance than synchronized in some cases. Note, however, that the volatile keyword cannot replace the synchronized keyword because the volatile keyword does not guarantee the atomicity of the operation. In general, the following 2 conditions are required to use volatile:

1) The write operation to the variable does not depend on the current value

2) The variable is not included in the invariant with other variables

Here are a few scenarios for using volatile in Java.

①. Status Flag Amount

123456789 volatile boolean flag = false &NBSP; //thread 1 while (!flag) { &NBSP;&NBSP;&NBSP;&NBSP; dosomething (); &NBSP;&NBSP; // Thread 2 public void setflag () { &NBSP;&NBSP;&NBSP;&NBSP; flag = true

Terminates the thread based on the status token.

②. Double check in singleton mode

1234567891011121314151617 class Singleton{    private volatile static Singleton instance = null;    private Singleton() {    }     public static Singleton getInstance() {        if(instance==null) {            synchronized (Singleton.class) {                if(instance==null)                    instance = new Singleton();            }        }        return instance;    }}
Why use the volatile modifier instance?

The main reason is instance = new Singleton (), this is not an atomic operation, in fact in the JVM this sentence probably did the following 3 things:

1. Allocating memory to instance

2. Call Singleton's constructor to initialize member variables

3. Point the instance object to the allocated memory space (instance is non-null after performing this step).

However, there is an optimization of command reordering in the JVM's immediate compiler. In other words, the order of the second and third steps above is not guaranteed, and the final order of execution may be 1-3-2. If it is the latter, then after 3 execution, 2 is not executed, before the thread two is preempted, then instance is non-null (but not initialized), so the thread two will return directly to instance, then use, and then logically error.

Java Concurrency Programming and volatile

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.