Tuesday, December 14, 2010

Thread Working For Fixed Time Even In Case Of Exceptions (UncaughtExceptionHandler)

Somebody asked me how to keep running a thread for a fixed interval even there is some exception.
At that point of time i had no answer.

But now i think, i have the answer.

And this can be done using the interface Thread.UncaughtExceptionHandler.

UncaughtExceptionHandler is an inner interface of Thread class.

We can implement it and set it using the method setUncaughtExceptionHandler() of Thread class.

Here is an example.

class MyThread extends Thread {
 
private boolean flag; 
protected int counter=0;
MyThread(int counterInitialValue) {
   this.counter = 0;
}

public MyThread(Runnable r,int counterInitialValue) {
   super(r);
   this.counter = counterInitialValue;
   this.flag = true;
}

@Override
public void run() {
 if (!flag) {
 flag = true;
 System.out.println("Thread Exec Started");
 } else {
 System.out.println("Thread Running Again");
 }
 while (counter <20) {
  counter++;
  try {
   Thread.sleep(1000);
  } catch (InterruptedException e) {
    e.printStackTrace();
  }
// do some work here....
  if(counter % 3 == 0){
    System.out.println(" Thread working , 
          counter value is : "+ counter);
  }
  if (counter == 10) {
   throw new RuntimeException("I am throwing exception");
  }
   
  }
 }
}

class MyThreadExceptionHandler implements 
        Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, 
                              Throwable e) {
  MyThread oldThread = (MyThread) t;
  System.out.println("Received exception "+ 
                           e.getMessage());
  if (oldThread.counter < 20) 
  {
   System.out.println("Value of counter 
       (restart required) : " + oldThread.counter);
   
   MyThread newThread = new MyThread(oldThread,11);
   
   newThread.start();
  } 
  else 
  {
   System.out.println("Thread work done");
   System.out.println("Value of counter : " +
                       oldThread.counter);
  }
 }
}



public class ThreadRunningForFixedTime {
public static void main(String[] args) {
  MyThread th = new MyThread(0);
  MyThreadExceptionHandler handler = 
          new MyThreadExceptionHandler();
  th.setUncaughtExceptionHandler(handler);
  th.start();
 }
}

1 comment:

  1. Think tasks - not threads.
    What about someone wating on the thread(join)?

    ReplyDelete