Sunday, September 4, 2016

JAVA MULTITHREADING: Basic Thread Synchronization using Volatile

This is about graceful shutdown of a thread from another thread!
Use this when you do not want threads having their own cached copies of variables!!
  • Imagine Processor class which extends Thread class. 
  • It overrides the run() method and introduces a freaking new boolean variable calling running.
  • It has another method too called shutdown().
  • Now, overridden method run() is basically a while loop running based on the value of running variable.
  • As defined using Scanner class inside main() method, once the user presses an enter key, the value of the running variable is made false and the execution of the run() method stops.

import java.util.Scanner;

public class App {
 public static void main(String[] args){
  Processor processor = new Processor();
  processor.start();
  System.out.println("Press enter to stop!");
  
  Scanner scanner = new Scanner(System.in);
  scanner.nextLine();
  processor.shutdown();
  scanner.close();
 }
}

class Processor extends Thread{
 private /*volatile*/ boolean running = true;
 
 public void run(){
  while(running){
   System.out.println("Hello");
   
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 
 public void shutdown(){
  running = false;
 }
}



In some cases, to optimize the execution, the JVM caches the values of variables like running.
This might lead to run() method never knowing, if at all, there’s a change in the value of running FROM ANOTHER THREAD!

This caching problem for variables can be solved by marking the variables with keyword ‘volatile’. PROBLEM SOLVED!

No comments:

Post a Comment