Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Future Task rejected from ThreadPoolExecutor

I have a ThreadPoolExecutor and I submit a task to it.

private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1));

This code submits the Runnable to the ThreadPoolExecutor.

 protected void waitAndSweep(final String symbol) {

    runnable = new Runnable() {
      public void run() { /* irrelevant code */ }
    };

    try {
      Future<?> self = threadPoolExecutor.submit(runnable);
      futures.add(self);
    } catch (RejectedExecutionException re) {
      /* this exception will be thrown when wait and sweep is called more than twice.
       * threadPoolExecutor can have one running task and one waiting task.
       */
    } catch (Exception e) {
      logEvent(StrategyEntry.ERROR, "waitAndSweep", symbol, "Exception caught...", e);
    }
  }

The following code stops the task.

protected synchronized void stop(StrategyEntry entry) throws Exception {
    for (Object future : futures) {
      ((Future<?>) future).cancel(true);
    }
    futures.clear();

    threadPoolExecutor.shutdown();
}

The problem here is: When I try to stop the task, I am getting following exception:

Task java.util.concurrent.FutureTask@3a475611 rejected from java.util.concurrent.ThreadPoolExecutor@216393fb[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 1]

like image 422
MMPgm Avatar asked Feb 11 '16 11:02

MMPgm


People also ask

Which method can be used to stop the Threadpool executor?

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 the use of ThreadPoolExecutor?

ThreadPoolExecutor is an ExecutorService to execute each submitted task using one of possibly several pooled threads, normally configured using Executors factory methods. It also provides various utility methods to check current threads statistics and control them.

How do you handle RejectedExecutionException?

If you have constrained your thread pool to only allow a certain number of concurrent threads (generally a good thing), then the application needs to somehow push-back on the calling code, so when you receive a RejectedExecutionException from the ThreadPoolExecutor you need to indicate this to the caller and the caller ...


1 Answers

The problem is that you shutdown() the excutor in the stop method. If you just want to wait for the task to complete, use Future.get(). When a executor is shut down, tasks can no longer be submitted to it.

shutdown() should only be used when you actually want to terminate the application.

like image 194
randers Avatar answered Oct 04 '22 04:10

randers