有没有办法在
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);
}