Is there an activity failure that occurs in concurrency in Java 8

I will try to reproduce the code mentioned in the following valid Java (Second Edition)

public class StopThread {
   private static boolean stopRequested;

   public static void main(String args[]) {
      Thread backgroudThread = new Thread(new Runnable(){
             public void run() {
                int i = 0;
                while(!stopRequested) {
                       i ++;
                }
             }
      });
      backgroudThread.start();

      TimeUnit.SECONDS.sleep(1);
      stopRequested = true;
   }
}

According to the author's description, when you run the above process segment, the backgroupdthread will not terminate But I can't reproduce it on a machine that sets up the Java 8 environment Has this problem been optimized in the latest version of Java?

Update I'll try again in the Linux operating system (RedHat) It never ends I used to run it in the win7 operating system corei5 It always ends

PS: in the Linux operating system (RedHat) If you run according to the above code, the program will not terminate But if I add "system. Out. Println (I)" after "I" in the "while" loop At this time The program will always terminate This is my new discovery If you know why, please post your answer I will continue to study these series of problems in depth until I find the real reason

Solution

Then, if more accurate, the author writes:

Now you can still argue that he obviously didn't run the program "forever", but you see

By the way, on my machine, the program will never terminate (JDK 1.7.0_45). By the way 2: if we want it to terminate, all we have to do is declare stoprequested as volatile

Update: in order to provide more context for people who don't have this book (you really deserve it!), The author later explained that this might happen because the compiler detected that stoprequested was not changed locally, so the following optimizations were allowed:

while(!stopRequested) {
      i ++;
}

Change to:

if (!stopRequested)
    while(true) {
          i ++;
    }

JVM hotspots perform this optimization (called promotion) If you want to delve into why it is a legitimate optimization, you should do some reading: JLS § 17.4 3 Programs and Program Order

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>