5

Why we can't see the stacktrace in this example ?

public class NoStackTraceTester implements Runnable  {
    private static final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();

    private ScheduledFuture<?> lifeCheckFuture;

    @Override
    public void run() {
        lifeCheckFuture = startLifecheck();
    }

    private ScheduledFuture<?> startLifecheck()
    {
        Runnable lifeCheck = new Runnable()
        {
            @Override
            public void run()
            {
                System.out.println("sending lifecheck ...");
                throw new RuntimeException("bang!");
            }
        };
        return scheduler.scheduleAtFixedRate(lifeCheck, 1000, 1000, TimeUnit.MILLISECONDS);
    }

    public static void main(String[] args) {
        new NoStackTraceTester().run();
    }
}

If you try to comment the exception you will the the repeative task of the lifecheck function. But if an exception is thrown, thread stop but with no detail :(

Do you have an idea why ?

4

3 回答 3

3

ExecutorService 将任何捕获的 Throwable 放置在 Future 对象中。如果你检查这个,你可以看到抛出了什么异常。这并不总是可取的,因此您可能必须在 run() 方法中捕获并处理或记录任何异常。

注意:一旦异常逃逸,该任务将不再重复。

Runnable lifeCheck = new Runnable() {
    @Override
    public void run() {
        try {
            System.out.println("sending lifecheck ...");
            throw new RuntimeException("bang!");
        } catch(Throwable t) {
            // handle or log Throwable
        }
    }
};
于 2012-10-15T13:18:55.773 回答
1

如果你想要一个异常报告,你必须自己插入处理代码。ExecutorService 不会自动将异常跟踪发送到标准输出,这很好,因为这在生产代码中很少需要。

基本上,这是一种方法:

public void run()
{
   try {
     System.out.println("sending lifecheck ...");
     throw new RuntimeException("bang!");
   } catch (Throwable t) { t.printStackTrace(); }
}
于 2012-10-15T13:15:11.853 回答
0

ThreadPoolExecutor 中的 afterExecute() 方法可以被覆盖:

class MyThreadPoolExecutor extends ThreadPoolExecutor {
    public MyThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
            TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    public void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        // If submit() method is called instead of execute()
        if (t == null && r instanceof Future<?>) {
            try {
                Object result = ((Future<?>) r).get();
            } catch (CancellationException e) {
                t = e;
            } catch (ExecutionException e) {
                t = e.getCause();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        if (t != null) {
            // Exception occurred
            System.err.println("Uncaught exception is detected! " + t
                    + " st: " + Arrays.toString(t.getStackTrace()));
        }
        // ... Perform cleanup actions
    }
}

final class MyTask implements Runnable {
    @Override public void run() {
        System.out.println("My task is started running...");
        // ...
        throw new ArithmeticException(); // uncatched exception
        // ...
    }
}

public class ThreadPoolExecutorHandler {
    public static void main(String[] args) {
        // Create a fixed thread pool executor
        ExecutorService threadPool = new MyThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>());
        threadPool.execute(new MyTask());
        // ...
    }
}

来源:https ://medium.com/@aozturk/how-to-handle-uncaught-exceptions-in-java-abf819347906 (请注意,我将此处发布的代码修改为不重新执行,因为问题只要求堆栈跟踪印刷)

于 2019-09-05T13:58:42.397 回答