6

I have a ExecutorService:

private final ExecutorService listenDataExecutorService = 
                              Executors.newSingleThreadExecutor();

In same case I need executor to stop doing his job. For this I call listenDataExecutorService.shutdown();

Then after some time, I need this executor to do this job again. But when I call listenDataExecutorService.execute() exception is thrown.

How can I execute new task for executor after shutdown ?

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
Jim
  • 8,874
  • 16
  • 68
  • 125

2 Answers2

6

Once an executor service has been shut down it can't be reactivated. Create a new executor service to restart execution:

listenDataExecutorService = Executors.newSingleThreadExecutor();

(You'd have to drop the final modifier though.)

Another option is to cancel all pending tasks instead, and then reschedule them when you want to resume execution.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Is there other way to clean current executor tasks except "shutdown" ? – Jim Oct 01 '14 at 14:06
  • If you use ThreadPoolExecutor you have a remove(Runnable) operation. – aioobe Oct 01 '14 at 14:08
  • Thinking about this a bit more, I'd suggest you create a higher level service with start/pause/resume/stop methods which in turn manage en executor service internally. – aioobe Oct 01 '14 at 14:18
0

First you have to remove final access level modifier to re-create ExecutorService at latter stage. final modifier does not allow you to change the reference of ExecutorService later during re-initialization.

In same case I need executor to stop doing his job. For this I call listenDataExecutorService.shutdown();

You have to call three methods in a right sequence to shutdown the ExecutorService: shutdown, awaitTermination, shutdownNow

Have a look at below post:

How to properly shutdown java ExecutorService

Then after some time, I need this executor to do this job again. But when I call listenDataExecutorService.execute() exception is thrown.

How can I execute new task for executor after shutdown ?

Before you call execute on that ExecutorService, that service should not be in shutdown state. Make sure that ExecutorService is in proper state to accept tasks => Your application code should properly handle "shutdown" and "re-creation" of ExecutorService.

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211