有效地使用UncaughtExceptionHandler [英] Using UncaughtExceptionHandler effectively

查看:164
本文介绍了有效地使用UncaughtExceptionHandler的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我已经了解了这个Java 1.5的功能,我开发了一个使用这个代码的示例代码。我的目标是在由于未捕获的异常而重新启动线程。

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();
    }
}

这里的文件阅读器只是包含一个读取的例程一个文件和打印内容。我正在模拟一个未捕获的异常,使该文件名为null。

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.

然后我的CustomExceptionHandler类如下。

Then my CustomExceptionHandler class is as follows.

public class CustomExceptionHandler implements Thread.UncaughtExceptionHandler {

    public void uncaughtException(Thread t, Throwable e) {
        ThreadManager.startThread();
    }
}

但是在这里我发现了一个问题。在未捕获的异常之后,线程处于睡眠状态。我通过使用分析器验证了它。所以创建新线程会随着时间的推移填满我的内存。使system.gc()后跟t = null不起作用。

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....

谢谢

推荐答案

我建议的方法是不让异常从你的线程泄漏出来。未捕获的异常处理程序是一个漂亮的工具,但是,如果您使用它来确保您的线程正在运行,我建议您有一个设计或代码问题。你的线程正在死亡可怕,只是忽略它,并重新启动一个新的在它的位置可能不是你想做的,即使你能够弄清楚睡眠线程问题。

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.

想象一下,您的线程中的问题不在于您的 main()方法 - 您是否会将相同的异常泄露出来,并杀死您的应用程序吗?如果没有,你会如何减轻这个问题呢?你不会写一个异常处理程序,再次调用 main()无论你做什么,那就是你在线程中应该做的。

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.

这篇关于有效地使用UncaughtExceptionHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆