开发者

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

When I create a thread by calling ScheduledExecutorService.schedule(), it never t开发者_运维知识库erminates 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?


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.


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.


You need to call scheduledExecutorService.shutdown() to stop the execution. Otherwise it is restarted every second.

(EDITED: see comments)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜