Special rules for Java memory model and thread-volatile variables

Source: Internet
Author: User

I. SUMMARY of rules

The lightweight synchronization mechanism, variable v is the volatile type.

(1) In working memory, the most recent value is flushed from main memory before each use of V to ensure that the modified values of the variable v are visible to other threads.

(2) In working memory, each change to V is immediately synchronized to the main memory, to ensure that other threads see their changes to the variable v.

(3) Changes to volatile variables will not be ordered to the east-West month, to ensure that the code is executed in the same order as the program.

The read performance of volatile variables is not the same as that of ordinary variables, but the performance of write operations is somewhat worse, but in most cases it is better than locking.

Two, two features

When a variable is defined as volatile, it has two features:

    • Ensure the visibility of this variable to all threads

That is, when a thread modifies the value of the variable, the new value is immediately known to other threads. The normal variable is passed through the main memory, such as a thread a modifies a normal variable, then writes back to the main memory, and another thread B reads the new value from the main memory, and then the new variable is visible to thread B.

We can say that the volatile variable has no consistency in the working memory of each thread (in the working memory of each thread, the volatile variable can also be inconsistent, but because each use is preceded by a flush, it does not see a case, So we can assume that there is no consistency problem, but the operation in Java is not atomic, and the operation of the volatile variable is not safe in the concurrency case.

For example

Package com.company;/** * Created by LSJ on 2015/9/7. */public class Volatiletest {public    static volatile int race =0;    public static void Increase () {        race++;    }    private static final int COUNT =20;    public static void Main (String [] args) {        System.out.println ("Begin");        Thread [] threads = new Thread[count];        for (int i=0;i<count;i++) {            threads[i]= new Thread (new Runnable () {                @Override public                void Run () {                    for (int i=0;i<100;i++) {                        increase ();}}}            );            Threads[i].start ();        }        The yield () in thread is to suspend the current thread, go into a ready state,        //Let the system's thread scheduler reschedule once, where the main thread is already queued.        while (Thread.activecount () >1) {            Thread.yield ();        }        System.out.println (race);    }}

The result of the output is not necessarily correct.

The problem is that in race++, we can get the byte code of this sentence:

public static void increase (); Code:stack =2,locals=0, args_size =0 0:  getstatic    #13;  Field race:i 3:  iconst_1     4:  iadd  5:  putstatic    #13;  Field race:i     8:  

Reason for failure: When Getstatic takes race to the Operation Stack, volatile guarantees that the value of race is correct at this time, but while executing iconst_1, Iadd, other threads may have modified race, and the value in the operand stack becomes outdated data , so the putstatic directive may simply write the incorrect race to memory. In fact, the bytecode here is not necessarily atomic, but it can already explain the problem.

Because volatile can only guarantee visibility, the operation scenario must meet the following criteria in order to use volatile:

(1) The result of the operation does not depend on the current value of the variable, or can ensure that only a single thread modifies the value of the variable.

(2) Variables do not need to participate in invariant constraints with other state variables.

In other cases we need to lock the operation.

    • Disable command reordering optimization

Special rules for Java memory model and thread-volatile variables

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.