java - 如何使用 ScheduledExecutorService 处理重复任务中的错误?

标签 java multithreading concurrency error-handling scheduledexecutorservice

我有一个 ScheduledExecutorService ,它调用 Runnable定期通过 scheduleWithFixedDelay() (可以使用 scheduleAtFixedRate() 代替)。

我现在正在考虑如果发生错误该怎么办。如果它是无法轻易从(*)恢复的东西,我希望选择停止所有进一步的调用,但不确定执行此操作的最佳方法。

明显检查的异常不能从 Runnable 中抛出,因此希望获得有关如何从以下选项中进行选择的指导:

scheduledFuture.cancel(false);
...or...
scheduledFuture.cancel(true);
...or...
scheduledExecutorService.shutdown();
...or...
scheduledExecutorService.shutdownNow();
...or...
Throw a custom RuntimeException myself?
...or...
Something else?

(*) 想知道一般情况,但如果有人感兴趣,我当前正在查看的已检查异常是 ParserConfigurationExceptionDocumentBuilderFactory.newDocumentBuilder() 抛出。如果抛出此错误,则表明存在严重问题,因此我基本上希望调度完全停止,而不是每次都可能重复错误。

最佳答案

您可以使用 Callable以及 Future也许。这将使您可以从异步任务中抛出已检查的异常,但仍然可以根据每个任务的需要捕获和处理。

如果您使用这种方法,那么允许任务本身决定如何处理异常可能是最有意义的。请参阅这个答案:

但是,如果您想在任务本身之外处理异常,那么我认为每个任务都需要另一个线程。这是一种可能的选择:

    ScheduledExecutorService scheduleExecutor;
    scheduleExecutor = = Executors.newScheduledThreadPool(10); // or whatever

    ExecutorService workerExecutor;
    workerExecutor = Executors.newSingleThreadExecutor(); // or whatever

    public void schedule(final long fixedDelay) {

      scheduleExecutor.scheduleWithFixedDelay(new Runnable() {

        @Override
        public void run() {

            Future<Void> future = workerExecutor.submit(new Callable<Void>() {

                @Override
                public Void call() throws Exception {

                    // Do work here. Throw appropiate exception as needed.

                    return null;
                }
            });

            // Now you can catch and handle the exception in whatever
            // way you need to. You can cancel just this task (which is likely
            // redundant by this point), or you can choose to shutdown
            // all other scheduled tasks (which I doubt is what you want).

            try {
                future.get();
            } catch (Exception e) {
                future.cancel(true);
            }

        }
    }, 0, fixedDelay, TimeUnit.MILLISECONDS);

}

关于java - 如何使用 ScheduledExecutorService 处理重复任务中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13993911/

相关文章:

java - 如何在 Java 中使用 RUDP 创建一个简单的服务器客户端应用程序?

Java GridBagLayout 对齐按钮

multithreading - 1024 个 CPU 的内核调度

c++ - 标准实验锁存器和屏障使用 ptrdiff_t

java - Netbeans 和 EOF

Java TCP 客户端重复连接导致 EMFILE 错误

iphone - 如何在 iOS 上取消 applicationDidEnterBackground 中的工作线程

java - 为什么 Spring Batch 为每个线程使用 1 个数据库连接?

android - Android 中 IntentService 的多个实例

java - 如何从 J2EE Web 应用程序中的服务层调用 DAO 方法