I'm currently refactoring a chunk of code that pretty much goes like this:
public static void main(String... args) {
while (true) {
// Do something...
Thread.sleep(300000); // Every 5 minutes
}
}
The idea is that I want to use a ScheduledExecutorService
to do the running of the code:
public static void main(String... args) {
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(new Task(...), 0, 5, TimeUnit.MINUTES);
}
There are a few concerns that I have with this, though: firstly, the fact that the program "terminates" (as in main()
returns) after scheduling, but the JVM is kept alive because the ScheduledExecutorService
remains running. I believe that this is intentional, in order to maintain the old code's behavior of "keep running until terminated from the outside", but I believe that I would have to install a shutdown hook to ensure that the ScheduledExecutorService
shuts down properly. Will that actually be the case, or will "killed from the outside" also prevent execution of the shutdown hook?
Secondly, I'm also squeamish about having a shutdown hook in the first place. If I had code like
try {
while (true) {}
} finally {
// Shutdown hook code goes here instead
service.shutdown();
if (!service.awaitTermination(1, TimeUnit.SECONDS)) {
service.shutdownNow();
}
}
will the same "killed from the outside" concern as above still exist?
EDIT: Yes, the original program loops through without ever breaking through the loop; it was only meant to be terminated from, say, SIGINT (control-C in a terminal). It is a rather poorly-defined termination condition, but that is the only thing that I have right now...