Is It Okay To Add A Thread.sleep Inside an !.isTerminated loop?

The typical ExecutorService example shows using a while loop that simple tests isTerminated after a shutdown request. My thinking is that the while loop is being called too often to do not much of anything.

Would it be okay to place a Thread.sleep(x) within the loop so it frees up some processor resources?

es.shutdown();
while (!es.isTerminated()) {
    try {
        Thread.sleep(60000);
    } catch (InterruptedException e) {
        e.printStackTrace();
        return;
    }
}

Upvotes: 2

Views: 130

Answers (2)

Andy Turner
Andy Turner

Reputation: 140494

The main things wrong here are:

  • You only check for termination every 60s. So, if you just miss the change from not terminated to terminated, you could be waiting for up to 60s too long
  • You don't reinterrupt the current thread when you are interrupted. If you're interrupted, you (almost) always want to preserve the fact that you were interrupted, in order that the code which called this code can know that it needs to stop what it's doing. This is ideally done by allowing the InterruptedException to propagate, but alternatively by re-interrupting the thread.

It would be better to use

es.awaitTermination(60, SECONDS);

in order to stop as soon as the executor terminates.

And, when you catch the interruption:

Thread.currentThread().interrupt();

to allow it to propagate.

Or, forgo the loop and just sleep for a really long time:

es.awaitTermination(Long.MAX_VALUE, SECONDS);

Upvotes: 3

Martín Zaragoza
Martín Zaragoza

Reputation: 1817

Within this specific scenario, using the Thread.sleep would only make sense if you absolutely need the executor service to be dead before you perform any additional logic.

If this is not the case then pausing the main thread with sleep while the executor is shutting down does not make much sense, the Jvm will not free many resources while doing that Thread.sleep(60000)

Upvotes: 0

Related Questions