In depth synchronous access to Shared variable data analysis

  • 2020-04-01 02:07:02
  • OfStack

If access to Shared mutable data is not synchronized, the consequences are dire, even if the variable is atomically readable.
Now consider a thread synchronization aspect. For Thread synchronization, the Java class library provides a method called thread.stop, but this method is not recommended because it is inherently unsafe. A better method is to use Polling, such as the following.

import java.util.concurrent.TimeUnit;
public class StopThread {
 

 private static boolean stopRequested;

 public static void main(String[] args) 
  throws InterruptedException{

  Thread backgroundThread = new Thread(new Runnable() {

   @Override
   public void run() {

    int i = 0;
    while(!stopRequested){
     i++;
     System.out.println(i);
    }
   }
  });
  backgroundThread.start();
  TimeUnit.SECONDS.sleep(1);
  stopRequested = true;
 }
}

You might think that after this program runs for about a second, the main thread sets the stopRequested to true, causing the new thread in the background to stop, but it doesn't, because the background thread doesn't see the change in this value, so it will continue to loop wirelessly, which is the result of not synchronizing the data. So let's do this synchronously.

import java.util.concurrent.TimeUnit;
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() {

   @Override
   public void run() {

    int i = 0;
    while(!stopRequested()){
     i++;
     System.out.println(i);
    }
   }
  });
  backgroundThread.start();
  TimeUnit.SECONDS.sleep(1);
  requestStop();
 }
}

This enables synchronization of the data, and it is worth noting that both the write method (requestStop) and the read method (stopRequested) need to be synchronized, otherwise they are still not truly synchronized.
In addition, we can use the variable modifier volatile to make synchronization easier.

import java.util.concurrent.TimeUnit;
public class StopThread {
 

 private static volatile boolean stopRequested;

 public static void main(String[] args) 
  throws InterruptedException{

  Thread backgroundThread = new Thread(new Runnable() {

   @Override
   public void run() {

    int i = 0;
    while(!stopRequested){
     i++;
     System.out.println(i);
    }
   }
  });
  backgroundThread.start();
  TimeUnit.SECONDS.sleep(1);
  stopRequested = true;
 }
}

Related articles: