10

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]

6
  • Do you call shutdown() on this executor anywhere? Commented Feb 11, 2016 at 11:47
  • You are creating a backing queue with capacity 1 - is there some other task already in there? Commented Feb 11, 2016 at 11:52
  • 1
    @AndyTurner From the error he gets it is clearly visible that the executor is in the Terminated state - that what is causing the exception. Commented Feb 11, 2016 at 11:57
  • If some other task already in there, executor will reject the task and it will be caught by catch block and it will be never displayed in the GUI. Commented Feb 11, 2016 at 11:58
  • 1
    What line in your code throws the exception? What is the type of the exception? Commented Feb 11, 2016 at 13:19

1 Answer 1

14

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.

Sign up to request clarification or add additional context in comments.

3 Comments

When executor is shutdown, I do not want any new task to be submitted
@MMPgm From your question, it is not entirely clear what you expect the stop() method to actually do. Maybe you can clarify that?
Stop method should kill all waiting task and it should not accept any other task. I just wanted to know what is the possible case for the exception to occur.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.