Using UncaughtExceptionHandler effectively

二次信任 提交于 2019-12-30 03:37:13

问题


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


回答1:


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.




回答2:


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!



来源:https://stackoverflow.com/questions/1535923/using-uncaughtexceptionhandler-effectively

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!