Future task deviates from ThreadPoolExecutor

I have a ThreadPoolExecutor , and I'm sending him a job.

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

This code sends the Runnable to 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 get the following exception:

java.util.concurrent.FutureTask@3a475611 rejected from java.util.concurrent.ThreadPoolExecutor@216393fb [Finished, pool size = 0, active threads = 0, tasks with posts = 0, completed jobs = 1]

+5
source share
1 answer

The problem is that you are shutdown() excutor in the stop method. If you just want to wait for the task to complete, use Future.get() . When the artist shuts down, tasks can no longer be sent to him.

shutdown() should only be used when you really want to shut down the application.

+5
source

Source: https://habr.com/ru/post/1242767/


All Articles