Java:忽略了 ScheduledExecutorService 的 RuntimeException

Java: Ignored RuntimeException with ScheduledExecutorService

简介

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

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

目标

当调度出现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

所有这些异常扩展 RuntimeException

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

嗯,既然任务只是抛出一个 RuntimeException,那么这个怎么样?

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

请放心,此代码会引发异常。您可以尝试使用此代码:

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!");
    }

}

请注意,此解决方案按规定“将问题告知用户”并“停止整个程序”。