Pause ScheduledExecutorService

假如想象 提交于 2019-12-04 03:02:01

When an executor is shudown, it do no longer accept new task and wait for the current ones to terminate. But you don't want to terminate your executor, just pause it.

So what you can do, is that in your task you just deal with an empty queue. Because you task is only to be executed from time to time, CPU consumption will be near to 0 for it when there is no processing to do. this is the "if(!queue.isEmpty()) return;" from Peter Lawrey response.

Second, you use a blocking queue. That mean that if you call the method take() to get a queued element while the queue is empty, the executor thread will wait until some element is added to the queue automatically.

So:

  • You can't pause an executor an even it would complicate your code.
  • A blocking queue do by design exactly what you need: blocking the task if the queue is empty.
  • if you prefer you can just let the periodic task run and check if the queue isEmpty.
  • You should already use one or the other way in your task anyway otherwise you would have NullPointerException when the queue is empty.

You can do

if(!queue.isEmpty()) return; 

at the start.

If you are usin a ScheduledExecutorService which has a queue, why are you using it to add to another queue. Can you not just use the queue in the service?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!