Reprint Please specify source:http://blog.csdn.net/ns_code/article/details/17382679
one problem left in the article "Java Concurrent Programming Learning Note five: volatile variable modifier-unexpected problem" is that volatile only modifies the missedit variable, not the value variable, However, when the thread reads the value of values, it also reads the latest data. But in the online search of a lot of data are not, it seems that many people on the rules of volatile is not too clear, or only stay on the surface of the level, smattering.
Two days to see "Deep Java Virtual Machine--JVM advanced features and best Practices," chapter 12th: Java memory model and thread, and on the Internet to read the Java memory model related Materials, learned a lot of things, especially in the volatile part of this article to explain, The reason for the problem is determined.
First, make it clear: If you have two threads reading and writing volatile variables, thread A writes a volatile variable, and thread B reads the volatile variable, it can see that thread a writes to the volatile variable, the key here, It will not only see the write operation to the volatile variable, butall the shared variables that are visible before the a thread writes the volatile variable will immediately become visible to the B thread after the B thread reads the same volatile variable.
To look back at the problem in the article, because the volatile variable Missedit write operation in the program after the value variable write operation, and according to the volatile rule can not be reordered, so, thread B read by the change of Missedit, The change to thread a before its value variable is also visible to threads B.
Let's reverse the two lines of code VALUE=50 and Missedit=true, that is, missedit=true in front,value=50 in the back, so we'll get the result we want: the change in value will not be seen.
This should be the result of some revisions to the volatile rules after JDK1.2.
The modified code is as follows:
[Java]View PlainCopy
- Public class Volatile extends Object implements Runnable {
- //value variable is not marked as volatile
- private int value;
- //missedit variables are marked as volatile
- Private volatile Boolean missedit;
- //creationtime does not need to be declared volatile because it has not changed in code execution
- private long creationtime;
- Public Volatile () {
- Value = 10;
- Missedit = false;
- //Gets the current time, which is the time when the volatile constructor is called
- CreationTime = System.currenttimemillis ();
- }
- public Void Run () {
- Print ("Entering run ()");
- //loop to check if value is different
- While (value < ) {
- //If the value of Missedit is modified to true, exit the loop by break
- if (missedit) {
- //Before entering the Sync code block, assign value to Currvalue
- int currvalue = value;
- //Executes a synchronous statement on an arbitrary object to allow the thread to enter and leave the synchronized code block,
- //Compare the private copy of all variables in this thread with the original value in shared memory,
- //To detect changes in variables that are not marked with volatile
- Object lock = new Object ();
- synchronized (lock) {
- //Don't do anything
- }
- //Leave the Sync code block and assign the value at this time to Valueaftersync
- int valueaftersync = value;
- Print ("in Run ()-see value=" + Currvalue +", but rumor have it changed!");
- Print ("in Run ()-valueaftersync=" + valueaftersync);
- Break ;
- }
- }
- Print ("leaving Run ()");
- }
- public void Workmethod () throws interruptedexception {
- Print ("Entering Workmethod ()");
- Print ("in Workmethod ()-About to sleep for 2 seconds");
- Thread.Sleep (2000);
- //Change value only here
- Missedit = true;
- Value = 50;
- Print ("in Workmethod ()-Just set value=" + value);
- Print ("in Workmethod ()-About to sleep for 5 Seconds");
- Thread.Sleep (5000);
- //Change the value of Missedit only here
- Missedit = true;
- Value = 50;
- Print ("in Workmethod ()-Just set missedit=" + Missedit);
- Print ("in Workmethod ()-About to sleep for 3 seconds");
- Thread.Sleep (3000);
- Print ("Leaving Workmethod ()");
- }
- /*
- * The function of this method is to print out the MSG information to be printed before the execution of the program to this time, and to print the Code of the MSG thread
- */
- private void print (String msg) {
- //Using the Java.text package, this method can be simplified, but this is not used here
- Long interval = System.currenttimemillis ()-creationtime;
- String tmpstr = "" + (interval/ 1000.0) + "000";
- int pos = Tmpstr.indexof (".");
- String secstr = tmpstr.substring (pos- 2, POS + 4);
- String nameStr = "" + Thread.CurrentThread (). GetName ();
- NAMESTR = namestr.substring (Namestr.length ()- 8, Namestr.length ());
- System.out.println (secstr + " " + nameStr + ":" + msg);
- }
- public static void Main (string[] args) {
- try {
- //This constructor allows you to get the current time of the real-time clock
- Volatile vol = new Volatile ();
- //Stop 100ms to allow the real-time clock to get a little ahead of time so that the message created in print () prints at a time value greater than 0
- Thread.Sleep (100);
- Thread t = New Thread (vol);
- T.start ();
- //Hibernate 100ms, let the thread that just started has time to run
- Thread.Sleep (100);
- the//workmethod method runs in the main thread
- Vol.workmethod ();
- } catch (Interruptedexception x) {
- System.err.println ("One of thesleeps was interrupted");
- }
- }
- }
The results of the implementation are as follows:
Obviously, this is not in line with the second condition of using volatile: attach a good article about the correct use of the volatile keyword:http://www.ibm.com/developerworks/cn/ java/j-jtp06197.html
Turn: Java concurrency Programming 18: The correct analysis of volatile unexpected problems in the fifth chapter (with code)