Restart Threads in Java using UncaughtExceptionHandler - Java @ Desk

Wednesday, January 7, 2015

Restart Threads in Java using UncaughtExceptionHandler

Restart Threads in Java using UncaughtExceptionHandler

A lot of interview rooms listen to this question and a lot of candidates stop on a "No". Hope you have an elaborate answer after reading this post.

Threads have always been the most debated, misunderstood and under estimated component in Java. What makes this component even more mysterious is its ability to be controlled by the OS Scheduler of your underlying operating system. Threads are something that makes your code OS dependent and take away the ability of it to be "PLATFORM INDEPENDENT".

A very common interview question is can they be restarted. If you are handling the instantiation of your Thread,it cannot be restarted if it has finished its execution (terminated state). Done so, it throws a java.lang.IllegalThreadStateException exception.

public class ThreadState extends Thread {
 
 public void run(){
  System.out.println("I am in Run");
 }

 public static void main(String[] args) throws Exception{
  ThreadState threadState = new ThreadState();
  threadState.start();
  System.out.println(threadState.getStackTrace());
  Thread.sleep(100);
  
  System.out.println(threadState.getStackTrace());
  threadState.start();
  System.out.println(threadState.getStackTrace());
  
 }
}


Another direction this question could be answered is Thread Pools. You do not atomically handle thread starts when using Thread Pools. That logic is implemented by the thread Pool. Neither does the thread of a pool go to TERMINATED state when finished executing, it goes back to the pool and is made available for other tasks.

To add more to it, Threads cannot be exactly restarted but you can instantiate a new object of Thread and do so on your thread terminating condition. Most common reason threads can terminate is because of Exceptions. This can be achieved using UncaughtExceptionHandler Interface. It was introduced in Java 1.5 version.

Your interviewer might want an answer to a scenario which I quote now:
Let’s say you have a polling application which polls to check if an integer has a specific value. If you reach that specific value, your next task can start executing. You will have to keep re-polling until integer reaches that specific state. Below is the implementation:
class CustomExceptionhandler implements UncaughtExceptionHandler{

 public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
  System.out.println("I have reached the Re Instantiation Of Thread");
  new PollingThread().start();
  System.out.println("Re Instantiation Of Thread completed and Thread started"); 
 } 
}


public class PollingThread extends Thread {
 
 public void run(){
  this.setUncaughtExceptionHandler(new CustomExceptionhandler());
  int randomIntvalue = new Random().nextInt(5) ;
  if(randomIntvalue > 3){
   System.out.println("Polling successfull...Int value = "+randomIntvalue);
   System.out.println("Polling state achieved");
  }else{
   System.out.println("Polling un- successfull...Int value = "+randomIntvalue);
   System.out.println("Application needs to Repoll");
   intdivideByZero = 1/0;
  }
 }
 
 public static void main(String[] args){
  System.out.println("I am starting to Poll now");
  new PollingThread().start();
 }
}


setUncaughtExceptionHandler() method sets the objects of concrete UncaughtExceptionHandler type on your Thread. uncaughtException method is invoked every time an exception occurs in your Thread Execution. I have re-instantiated my Thread and started it in this method. Note , I have re-instantiated my Thread and not restarted it. So Threads cannot be restarted but they can surely be re-instantiated at thread terminating condition.



The above application could go out of memory if the randomIntvalue variable never achieves its desired value. Or in logical terms, the poll never gets over. So this thought could also be presented with a ThreadPool. I have built a Thread Pool of capacity 10 using java.util.concurrent.ExecutorService. If the thread does not have an explicit uncaught exception handler set, and the thread's thread group (including parent thread groups) does not specialize its uncaughtException method, then the default handler'suncaughtExceptionmethod will be invoked.By setting the default uncaught exception handler, an applicationcan change the way in which uncaught exceptions are handled (such as logging to a specific device, or file) for those threads that wouldalready accept whatever behavior the system provided.

class CustomExceptionHandler implements UncaughtExceptionHandler{

 public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
  System.out.println("I have reached the Re Instantiation Of Thread");
  PollingThread.submitThreadToPool(new PollingThread());
  System.out.println("Re Instantiation Of Thread completed and Thread started");
 }
}

public class PollingThread extends Thread {
 
 static ExecutorService executorService = Executors.newFixedThreadPool(10);
 
 public void run(){
  this.setUncaughtExceptionHandler(new CustomExceptionHandler());
  int randomIntvalue = new Random().nextInt(5) ;
  if(randomIntvalue > 3){
   System.out.println("Polling successfull...Int value = "+randomIntvalue);
   System.out.println("Polling state achieved");
   getThreadPool().shutdown();
  }else{
   System.out.println("Polling un- successfull...Int value = "+randomIntvalue);
   System.out.println("Application needs to Repoll");
   intdivideByZero = 1/0;
  }
 }
 
 public static void main(String[] args){
  Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler());
  System.out.println("I am starting to Poll now");
  executorService.execute(new PollingThread());
 }
 
 public static void submitThreadToPool(Runnable runnable){
  executorService.execute(runnable);
 }
 
 public static ExecutorService getThreadPool(){
  returnexecutorService;
  
 }

}


This post is written by
Komal Ahluwalia - Linkedin, Google Plus
She is a freelance writer, loves to explore latest features in Java technology.








No comments:

Post a Comment