Java doubts--the confusion of object lock

Source: Internet
Author: User

Java doubts, 77--the demon of the lock

The following procedure simulates a small workshop. The program first initiates a worker thread that will work until the stop time arrives (at least pretending to be at work), and then the program arranges a timer task (timer Task) to simulate a vicious boss who tries to stop the stopping time from coming. Finally, the main thread as a good boss will tell the worker to stop the time and wait for the worker to stop working. So what does this program print?


<span style= "FONT-SIZE:18PX;"      >public class Worker extends thread{private Long count = 0;      Private volatile Boolean quittingtime = false;              public void Run () {while (!quittingtime) {pretendtowork ();      } System.out.println ("Beer is good");                      } private void Pretendtowork () {try{thread.sleep (300);              SYSTEM.OUT.PRINTLN ("Product:" + (count++));      }catch (Interruptedexception ex) {}}//it ' Quitting time, wait for worker-called by good boss              synchronized void Quit () throws interruptedexception{Quittingtime = true;      Join ();      }//recsind quiting time-called by evil boss synchronized void Keepworking () {quittingtime = true; } public static synchronized void main (string[] args) throws interruptedexception{final Worker wor          ker = new Worker ();    Worker.start ();              Timer T = new timer (true);                      T.schedule (New TimerTask () {public void run () {worker.keepworking ();              }},500);              Thread.Sleep (400);      Worker.quit (); }}</span>

As explained in the book:

    • MS: worker thread to check the variable quittingtime domain to see if the stop time has arrived. This time there is no time to stop, so the worker thread will go back to "work".
    • 400MS: The main thread of being a good boss is going to call the worker thread's quit method. The main thread obtains the lock on the worker thread instance (because quit is a synchronized method), sets the value of Quittingtime to true, and invokes the join method on the worker thread. This call to the Join method will not return immediately, but will wait for the worker thread to finish.
    • 500m: As the malicious boss Timer task starts execution. It will attempt to invoke the worker thread's Keepworking method, but this call will be blocked because keepworking is a synchronous method, and the main thread is executing another synchronization method (the Quit method) on the worker thread at that time.
    • 600MS: Worker thread will check again if the stop time has arrived. Because the quittingtime domain is variable, the worker thread will definitely see the new value true, so it will print the Beer is good and end the run. This causes the main thread to return the call to the Join method, and then the main thread ends the run. The timer thread is behind the scenes, so it ends up running, and the whole program ends.
So, we will assume that the program will run less than 1 seconds, print Beer is good, and then the normal end. But when you try to run the program, you'll find that it's not printing anything, but it's always in a pending state (no end). What's wrong with our analysis?

In fact, there is nothing to ensure that several of these intersecting events will follow the timeline above. There is no guarantee of real-time (real-time) in both the Timer class and the Thread.Sleep method. This means that because the granularity of the timing is too coarse, the above events are likely to alternately overlap each other on the timeline. 100 milliseconds is a long time for a computer. In addition, the program is repeatedly suspended; it seems as if there is something else working, in fact, it does.

There is a fundamental error in our analysis. At 500ms, when a timer task is run as a malicious boss, its call to the Keepworking method is blocked based on the display of the timeline, because Keepworking is a synchronous method and the main thread is executing the synchronization method on the same object, quit ( Waiting in the Thread.Join). These are all right, keepworking is really a synchronous method, and the main thread is actually executing the synchronous quit method on the same object. Even so, the timer thread can still get the lock on this object and execute the Keepworking method. How did this happen?

The answer to the question relates to the realization of thread.join. This section is not found in the documentation for the method (JDK document), at least in the documents published so far, including version 5.0. Internally, theThread.Join method invokes the Object.wait method on the Thread instance that represents the join. This frees the lock on the object during the wait. In our program, this makes the timer thread, which is the malevolent boss, able to set the Quittingtime back to false, even though the main thread is executing the synchronous quit method at this point. The result is that the worker thread never sees the stopping time coming and it will run forever. The main thread of being a good boss will never return from the join method.

The root cause of the unexpected behavior of this program is that the author of the Workerthread class uses the lock on the instance to ensure that the Quit method and the Keepworking method are mutually exclusive, but this usage conflicts with the use of the lock within the superclass (Thread).

But after I run it many times, I can get normal results .....

I hope someone doubts me, maybe it's because I have a problem with my program.

Let's talk about small problems in writing programs!

The public class seventyseventh{//static class Worker extends thread{//need to write static, otherwise, defining work in main will make an error. Cause: Non-static variable cannot be referenced from a static context//private Long Count = 0;//private volatile Boolean quittingtime = false;/                              /experience volatile sometimes does not really implement lock mechanism//public void Run () {//while (!quittingtime) {//              Pretendtowork ();//}//System.out.println ("Beer is Good");// }//private void Pretendtowork () {//try{//THREAD.SL EEP (+//SYSTEM.OUT.PRINTLN ("Product:" + (count++));//}catch (Interrupt Edexception ex) {////}//}////it ' s quitting time, WA                      It for worker-called by good boss//synchronized Void Quit () throws interruptedexception{//             Quittingtime = true;//         Join ();//wait for thread to finish, that is, execute Run method//}////recsind quiting time-called by Evil boss// synchronized void keepworking () {//Quittingtime = true;//}//}//public static synchronized void main (string[] args) throws interruptedexception{//final worker worker = new Worker ( );//Must be the final type, otherwise, the call fails in new Timetask because the local variable worker is accessed from the inner class; Need to be declared as final type//Worker.start ();//Timer t = new timer (true);//T.schedule (new Timertas                      K () {//public void Run () {//worker.keepworking ();// }//},500);//Thread.Sleep (+);//Worker.quit ();//}//}



Java doubts--the confusion of object lock

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.