ScheduledExecutorService 任务完成后如何抛出异常?

问题描述 投票:0回答:0

有没有办法在

Exception
任务完成后立即抛出
ScheduledExecutorService
?无需冻结或暂停应用程序。

public synchronized void initializeApplicationResources(int totalAttempts, int secondsGap) throws DummyException {
    ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
    final AtomicInteger attemptsCount = new AtomicInteger(0);
    final AtomicReference<Exception> dummyError = new AtomicReference<>();
    scheduler.scheduleAtFixedRate(() -> {
        if (!isAppUp.get() && attemptsCount.get() <= totalAttempts) {
            try {
                System.out.println("Loading...");
                initializeApp();
            } catch (Exception e) {
                System.out.println("Loading failed.");
                dummyError.set(e);
            } finally {
                attemptsCount.getAndIncrement();
            }
            if (isAppUp.get()) {
                // throw exception that will eventually terminate the application
            }
        } else {
            // throw exception that will eventually terminate the application
        }
    }, 0, secondsGap, TimeUnit.SECONDS);
}
java multithreading executorservice runtimeexception
© www.soinside.com 2019 - 2024. All rights reserved.