You can’t avoid concurrency

What is the output of the following program?

public class StopThread {
   private static  boolean stopRequested;


   // what is the output ?
   public static void main(String[] args) throws InterruptedException {
      Thread backgroundThread = new Thread(new Runnable() {
         public void run() {
            int i = 0;
            while (!stopRequested) {
               i++;
            }

            System.out.println("done");
         }
      });
      backgroundThread.start();

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

This program will cause an infinite loop because stopRequested variable will not be shared between two threads. In order to share stopRequested variable between threads, we have 2 options.

1 – make stopRequested variable volatile 

2 – use synchronized method to access stopRequested variable, like below

 

public class StopThread {
   private static boolean stopRequested;

   private static synchronized void requestStop() {
      stopRequested = true;
   }

   private static synchronized boolean stopRequested() {
      return stopRequested;
   }

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

      TimeUnit.SECONDS.sleep(1);
      requestStop();
   }
}

The interesting point is if you use Graal VM then you don’t need to make above changes, Graal VM does the optimization automatically.

 

No Comments

Post a Comment

Comment
Name
Email
Website