相关疑难解决方法(0)

如何从Executors正确捕获RuntimeExceptions?

假设我有以下代码:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(myRunnable);
Run Code Online (Sandbox Code Playgroud)

现在,如果myRunnable抛出一个RuntimeExcpetion,我怎么能抓住它?一种方法是提供我自己的ThreadFactory实现,newSingleThreadExecutor()uncaughtExceptionHandler为其中的Threads 设置自定义.另一种方法是换myRunnableRunnable包含try-catch -block 的本地(匿名).也许还有其他类似的解决方法.但是......不知怎的,这感觉很脏,我觉得不应该这么复杂.有清洁的解决方案吗?

java concurrency executor runtimeexception

43
推荐指数
4
解决办法
2万
查看次数

ScheduledExecutorService和未捕获的错误

Code Review聊天中的讨论确定了ScheduledExecutorService的以下行为:

计划运行的任务失败并出现"严重"问题,但没有问题的报告,异常或日志.在其他情况下,应用程序通常会以错误终止.但是,在ScheduledExecutorService的上下文中,根本没有异常/错误"处理".

首先,要制造一个问题.以下类具有保证失败的静态初始化程序:

public class InitializerFault {

    private static final int value = Integer.parseInt("fubar");

    @Override
    public String toString() {
        return "" + value;
    }

}
Run Code Online (Sandbox Code Playgroud)

运行时:

public static void main(String[] args) {
    System.out.println(new InitializerFault());
}
Run Code Online (Sandbox Code Playgroud)

它产生(这正是我所期望的):

Exception in thread "main" java.lang.ExceptionInInitializerError
    at SimpleHandler.main(SimpleHandler.java:5)
Caused by: java.lang.NumberFormatException: For input string: "fubar"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at InitializerFault.<clinit>(InitializerFault.java:4)
    ... 1 more
Run Code Online (Sandbox Code Playgroud)

但是,当运行时:

private static final Thread buildThread(Runnable r) {
    Thread t = new Thread(r, "TestThread");
    t.setDaemon(true);
    System.out.println("Built thread …
Run Code Online (Sandbox Code Playgroud)

java exception scheduledexecutorservice

12
推荐指数
1
解决办法
416
查看次数