Search code examples
javamultithreadingthreadpooljava.util.concurrentfuturetask

Restarting cancelled tasks in ScheduledThreadPoolExecutor


I am creating tasks with ScheduledThreadPoolExecutor and adding the Futures to a list as below in my ThreadFactory class.

private static List<Future> futures;
........
ScheduledFuture sf = executor.scheduleAtFixedRate(obj, delayInMilliSec, repeatPeriod, TimeUnit.MILLISECONDS);

futures.add(sf);

Now when I want to cancel all the tasks , I do as below

public void cancelAllTasks(){

  Iterator<Future> fi = futures.iterator();

  while(fi.hasNext()){

     fi.next().cancel(true);
  }

}

Now how do I restart these tasks at a later point of time ?


Solution

  • Once a future is cancelled, the task cannot be resurrected at a later stage. A quick look at javadoc will explain the contract of the Future.

    To restart the tasks, schedule them again with the executor.