Talking about the understanding of volatile keyword in Java _java

Source: Internet
Author: User

Volatile this keyword probably many friends have heard, perhaps also all used. Before Java 5, it was a controversial keyword, because using it in a program often resulted in unexpected results. After Java 5, the volatile keyword was able to regain its vitality. Although the volatile keyword is literally easy to understand, it's not easy to use it well.

First, the preface

JMM provides a volatile variable definition, final, synchronized block to ensure visibility.
A variable decorated with volatile, the thread reads the variable's most-modified value each time it uses the variable. Volatile are easily misused for atomic manipulation. Write a few examples of the test, you can try.

Second, the main program

public class main{public
static void Main (string[] args) throws interruptedexception{
list<thread> Threadlist = new arraylist<thread> ();
for (int i=0; i<10; ++i) {
thread thread = new Thread (new Runnable () {
@Override public
void Run () {
Si Ngle. Holder.instance.add ();
}
);
Threadlist.add (thread);
Thread.Start ();
}
for (Thread thread:threadlist)
thread.join ();
System.out.println (single.holder.instance.x);
}

Three, single case mode test

1, no volatile, no synchronized situation

Class single{public
int x = 0;
public void Add () {
try {
TimeUnit.MILLISECONDS.sleep);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
++this.x;
}
public static class holder{public
static Single Instance = new single ();
}

Output: 8, 9, 10 have been shown. Can run more, try more, you will find different results.

2, there are volatile, no synchronized

Class single{Public
volatile int x = 0;
public void Add () {
try {
TimeUnit.MILLISECONDS.sleep);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
++this.x;
}
public static class holder{public
static Single Instance = new single ();
}

Output results: Up to 9 and 10.

3, no volatile, there are synchronized

Class single{public
int x = 0;
Public synchronized void Add () {
try {
TimeUnit.MILLISECONDS.sleep ()
} catch (Interruptedexception e) { C6/>e.printstacktrace ();
}
++this.x;
}
public static class holder{public
static Single Instance = new single ();
}

Output result: No matter how many times it is run, it is 10.

Iv. application of Volatile in DCL (double check Lock)

public class Lazysingleton {
private int somefield;
private static Lazysingleton instance;
Private Lazysingleton () {
This.somefield = new Random (). Nextint +1;//(1)
} public
static  Lazysingleton getinstance () {
if (instance = null) {//(2)
synchronized (lazysingleton.class) {//(3)
if (instance = null) {//(4)
instance = new Lazysingleton ();//(5)
}} return
instance;//(6)
}
public int Getsomefield () {return
This.somefield;//(7)
}
}

First of all, why this writing in Java is not workable!

Assuming that the thread Ⅰ is the first time the getinstance () method is invoked, and immediately after the thread Ⅱ also calls the GetInstance () method and the Getsomefield () method, we are describing the statement (1) of the thread Ⅰ that does not happen-before the thread Ⅱ statements (7). Thread Ⅱ When executing the statement (2) of the getinstance () method, because access to instance is not in the synchronized block, the thread Ⅱ may observe that the thread Ⅰ writes to instance at the statement (5). This means that the value of the instance may be empty or non-null. We first assume that the value of the instance is Non-null, and that the thread Ⅰ writes to instance, when the thread Ⅱ executes the statement (6) to return the value of the instance directly, and then invokes the instance () method on the Getsomefield. The method is also invoked in the absence of any synchronization, therefore, the entire thread Ⅱ operation is invoked without synchronization, indicating that there is no happen-before relationship between the thread Ⅰ statement (1) and the thread Ⅱ statement (7), which means that the thread Ⅱ in the execution statement (7) It is entirely possible to observe the value that thread Ⅰ writes to somefiled at statement (1), which is the problem with DCL. It's absurd, isn't it? DCL was originally meant to escape synchronization, it achieves this, and it is precisely because of this, it is finally punished, such a program there are serious bugs, although the probability of this bug is absolutely lower than the probability of lottery, and is fleeting, more frightening is, Even if it happened, you wouldn't think it was caused by DCL.

My understanding is that: threads I and Thread II both have their own working storage, thread I created the instance, the time to refresh to memory is indeterminate, so the thread Ⅱ in the execution statement (7) It is entirely possible to observe the thread Ⅰ the value written to somefiled at statement (1).

So because of the addition of a happen-before rule in Java 5:

• Write operations on the volatile field Happen-before subsequent read operations on the same field.

Using this rule we can declare instance as volatile, namely: private volatile static Lazysingleton instance;
According to this rule, we can get a thread-Ⅰ statement (5)-> a thread-ⅱ sentence (2) (that is, a thread), according to the single-threaded rule, the thread-Ⅰ statement (1)-> the thread-Ⅰ statement (5) and the language-thread-ⅱ sentence (2) The->-language thread-Ⅱ sentence (7), Then, according to the pass rule, the Ⅰ of the thread (1)-> the sentence (7), which indicates that the thread Ⅱ can observe the write value of the thread Ⅰ to the somefiled at the statement (1), and the program can get the correct behavior.

Add: There is no difference between the synchronization semantics of the final field and other variables before Java5, and in Java5, the final variable is bound to see the value set in the constructor if it is set to complete in the constructor (provided that the this reference is not compromised in the constructor). The problem with DCL is to see the default value of the object's member variable, so we can set the Lazysingleton Somefield variable to final so that it works correctly in Java5.

The above content is small to introduce the Java in the volatile keyword knowledge, hope to help everyone!

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.