How to make ScheduledExecutorService automatically stop a scheduled task

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();
    // do more configuration here...

    Thread.sleep(1000);

    scheduledTask.cancel(false);

    Thread.sleep(100);
    assertThat(scheduler.isTerminated(), is(true)); // ... so that this passes!?
}
+4
source share
1 answer

From ScheduledThreadPoolExecutor(actual type returned Executors.newScheduledThreadPool):

, . . , . , setRemoveOnCancelPolicy (boolean) true, .

ScheduledThreadPoolExecutor. , ScheduledExecutorService.

+4

Source: https://habr.com/ru/post/1538613/


All Articles