I got to know about this Java 1.5 capability recently and I developed a sample code to use this. My objective is to restart the thread when it gets dead due to an uncaught exception.
public class ThreadManager {
public static void main(String[] args) throws InterruptedException {
startThread();
}
public static void startThread(){
FileReaderThread reader = new FileReaderThread("C:\\Test.txt");
Thread thread = new Thread(reader);
thread.setUncaughtExceptionHandler(new CustomExceptionHandler());
thread.start();
}
}
Here the file reader is just contains a routine to read a file and print contents. I am simulating an uncaught exception by making the file name null inside that class.
Then my CustomExceptionHandler class is as follows.
public class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
ThreadManager.startThread();
}
}
But here I observed a problem. After the uncaught exception the thread is in Sleeping state. I verified it by using a profiler. So creating new threads would fillup my memory with time. Making system.gc() followed by a t = null didn't work.
So what is the best approach you suggest to deal with this scenario? I just need a new thread and I don't want any older threads any more....
Thanks