views:

84

answers:

2

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

+2  A: 

The approach I suggest is to not let exceptions leak out of your threads. The uncaught exception handler is a nifty tool, however, I suggest you have a design or code issue if you are using it to make sure your thread is running. Your thread is dying a horrible death and simply ignoring that and restarting a new one in its place is probably not what you want to do, even if you were able to figure out the sleeping thread issue.

Imagine instead of in your thread, the problem is with your main() method - would you let the same exception leak all the way out and kill your app? If not, what would you do to mitigate the issue? You wouldn't write an exception handler that calls main() again right? Whatever you would do, that is what you should do in your thread.

SingleShot
+1, don't let your program execute in an unknown state by blindly marching forward after an unexpected error!!
bobbymcr
+1  A: 

You should not restart the thread that is about to exit. The method is invoked when the given thread terminates. So you can only create and start a new thread. If you know about the threads class (by instanceof...) you can obtain the runnable from it and create a new thread in the terminating threads group and start it from the UncaughtExceptionHandler.

But aware: I would check for specific exceptions. A minimum can be: restart only if the throwable is a runtime exception, not an error!

Arne Burmeister