Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the thread started by ScheduledExecutorService.schedule() never terminate?

When I create a thread by calling ScheduledExecutorService.schedule(), it never terminates after executing the scheduled task.

For example the following program never quits:

public static void main(String[] args) {
  ScheduledFuture scheduledFuture = 
      Executors.newSingleThreadScheduledExecutor().schedule(new Callable() {

    public Void call() {
      doSomething();
      return null;
    }

  }, 1, TimeUnit.SECONDS);
}

public static void doSomething() {
}

Is this a JDK bug, or did I just miss something?

like image 797
moonese Avatar asked May 25 '10 09:05

moonese


People also ask

How do I exit ScheduledExecutorService?

If - instead of cancelling the beeper - you simply shutdown the scheduler after 9 seconds, your program will also exit normally.

How to terminate a thread in executor framework in Java?

When using an Executor, we can shut it down by calling the shutdown() or shutdownNow() methods. Although, it won't wait until all threads stop executing. Waiting for existing threads to complete their execution can be achieved by using the awaitTermination() method.

What is ScheduledExecutorService in Java?

public interface ScheduledExecutorService extends ExecutorService. An ExecutorService that can schedule commands to run after a given delay, or to execute periodically. The schedule methods create tasks with various delays and return a task object that can be used to cancel or check execution.


2 Answers

A scheduled task is either being executed or is waiting to be executed.

If the task is waiting to be executed, future.cancel() will prevent it from being executed (both cancel(true)/cancel(false)).

If the task is already being executed, future.cancel(false) will have no effect. future.cancel(true) will interrupt the thread that is executing that task. Whether this will have any effect is up to you, who will implement that task. A task may or may not respond to interruption depending on the implementation.

In order to make your task responsive to cancellation, you must implement doSomething() so that it will respond to interruption.

There are basically two way to do this:

1.Check interruption flag in your logic

public void doSomething(){
    stuff();
    //Don't use Thread.interrupt()
    if(Thread.currentThread().isInterrupted()){
        // We have an interruption request, possibly a cancel request
        //Stop doing what you are doing and terminate.
        return;
    }
    doLongRunningStuff();
}  

You must occasionally check for the interruption flag, and if interrupted, stop what you are doing and return. Be sure to use Thread.isInterrupted() and not Thread.interrupt() for the check.

2.Act upon Interrupted exception

public void doSomething(){
    try{
        stuff();
    }catch(InterruptedException e){
        // We have an interruption request, possibly a cancel request

        // First, preserve Interrupted Status because InterruptedException clears the 
        // interrupted flag
        Thread.currentThread.interrupt();

        // Now stop doing your task and terminate
        return;
    }

    doLongRunningStuff();
}

When you have any method that throws InterruptedException, be sure to stop what you doing and terminate when one is thrown.

Once you implement your methods in this way, you can call future.cancel(true) to cancel the execution of a running task.

like image 145
Enno Shioji Avatar answered Oct 16 '22 11:10

Enno Shioji


Your program never terminates because you create a ScheduledExecutorService, which holds a thread pool, but you never shut down the service. Therefore, the user threads in the thread pool are never terminated, and hence the VM keeps running forever.

To solve this problem, you need to call a shutdown() on the executor service. This can even be done directly after scheduling the task you want to execute:

public static void main(String[] args) {
  ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
  ScheduledFuture scheduledFuture = executorService.schedule(new Callable() {

    public Void call() {
      doSomething();
      return null;
    }

  }, 1, TimeUnit.SECONDS);
  executorService.shutdown();
}

This will execute the scheduled task normally and then terminate the thread in the pool.

like image 21
oberlies Avatar answered Oct 16 '22 09:10

oberlies