I have a task that should wait for a condition (OpenCms startup) and then notify some listeners. to do this I used an ExecutorService:
public void check(final ExecutorService executorService) {
executorService.submit(() -> {
waitForInitialization();
notifyListeners();
});
}
private void waitForInitialization() {
while (OpenCms.getRunLevel() < OpenCms.RUNLEVEL_4_SERVLET_ACCESS) {
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
the question is how to shutdown this executor. I could use awaitTermination but I should provide a timeout which I don't know exactly. it could vary from one environment to the other.
Based on the provided information, I'd clearly recommend an event-based approach. Especially knowing that in your own code there is a call like
notifyListeners(). In fact, that's the way to go.In summary, once the precondition is met somewhere in your app, just notify the listeners of this event. In your example, the "OpenCms run level" change is typically an event. So, just go for an
Observerpattern, or apub-submodel to observe or monitor these changes.If you modify your approach, you will not have to worry about the waiting time around the initialization, except if you wish to handle the absence of event specifically. That would be done again after some timeout, but with the advantage of not blocking an executor thread.