繁体   English   中英

Java:使用 ScheduledExecutorService 忽略 RuntimeException

[英]Java: Ignored RuntimeException with ScheduledExecutorService

介绍

我目前正在从事一个项目,该项目每 x 小时将数据从网站记录到数据库。

但是当数据库连接属性不好时,程序不会抛出RuntimeException假装一切正常。

我的代码:

    private static ScheduledExecutorService executeWithPeriod(Runnable runnable, int period) {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        executor.schedule(runnable, Math.max(1, period), TimeUnit.HOURS);
        return executor;
    }

runnable负责获取数据并将其保存到数据库中。

可能抛出的RuntimeException

  • DockerSecretVariableNotFoundException
  • EnvironmentVariableNotFoundException

所有这些异常都扩展RuntimeException

有人有将RuntimeException抛出到主线程的解决方案吗?

好吧,既然任务只是处理一个 RuntimeException,那么这个怎么样?

class MyRunnable implements Runnable {
    public void run() {
        throw new RuntimeException("mark my words");
    }
}

Rest 确保此代码引发异常。 您可以尝试使用以下代码:

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

但是通常 Runnables 在它们自己的线程中运行:

new Thread(new MyRunnable()).start()

所以现在也抛出了异常。 然而,它终止了线程 - 就是这样。

我从评论中回到我的问题:你想要实现什么?

您还没有证明需要多个线程,因此您可以消除并发线程之间信号传输的复杂性。 改为使用单个线程:

final class YourTask {

    public static void main(String... args) throws InterruptedException {
        YourTask task = new YourTask();
        while (true) {
            try {
                task.doYourThing();
            } catch (Exception ex) {
                ex.printStackTrace();
                break;
            }
            TimeUnit.HOURS.sleep(1L);
        }
    }

    private void doYourThing() throws Exception {
        System.out.println("I'm saving data from a website to a database!");
        throw new RuntimeException("Oh no! I can't read my configuration!");
    }

}

请注意,此解决方案按照指定“告诉用户问题”和“停止整个程序”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM