I use ScheduledExecutorServiceto close the network connection if it has been open for more than a few hours. However, in most cases, the network connection is closed before the timeout is reached, so I cancel ScheduledFuture. In this case, I also want the executing service to stop working and issue a thread pool.
To my surprise, this does not work out of the box: although I called shutdown()in the executing service after scheduling a task, the executing service does not stop automatically when its only scheduled task is canceled. From JavaDoc, ExecutorService.shutdown()this behavior may even be correct, since the task that was probably canceled was not completed:
void java.util.concurrent.ExecutorService.shutdown ()
Initiates an orderly completion of work in which previously assigned tasks are performed, but new tasks will not be accepted. A call has no additional effect if it is already turned off.
My question is, can this be changed: is it possible to configure the executing service to end automatically when its only scheduled task is canceled?
Or the same question, written as a JUnit test:
@Test
public void testExecutorServiceTerminatesWhenScheduledTaskIsCanceled() throws Exception {
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable task = new Runnable() {
@Override
public void run() {
}
};
ScheduledFuture<?> scheduledTask = scheduler.schedule(task, 2000, TimeUnit.MILLISECONDS);
scheduler.shutdown();
Thread.sleep(1000);
scheduledTask.cancel(false);
Thread.sleep(100);
assertThat(scheduler.isTerminated(), is(true));
}
source
share