Pause ScheduledExecutorService

I am using ScheduledExecutorService to perform a task that invokes a fixed speed service. A service may return some data to a task. The task stores data in a queue. Some other threads are slowly picking items from the queue.

 import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class EverlastingThread implements Runnable { private ScheduledExecutorService executorService; private int time; private TimeUnit timeUnit; private BlockingQueue<String> queue = new LinkedBlockingQueue<String>(500); public EverlastingThread(ScheduledExecutorService executorService, int time, TimeUnit timeUnit) { this.executorService = executorService; this.time = time; this.timeUnit = timeUnit; } public void run() { // call the service. if Service returns any data put it an the queue queue.add("task"); } public void callService() throws Exception { // while queue has stuff dont exucute??????????? executorService.scheduleAtFixedRate(this, 0, time, timeUnit); } } 

How to suspend the executorService service until the queue filled with the task is cleared.

+8
java scheduled-tasks executor
source share
2 answers

When the executor is turned off, he no longer accepts the new task and waits for the completion of the current ones. But you do not want to interrupt your artist, just pause him.

So what you can do is that in your task you are simply dealing with an empty queue. Since the task only runs from time to time, the CPU consumption will be around 0 for it if there is no processing. this is "if (! queue.isEmpty ()) return;" from Peter Lowry's answer.

Secondly, you use a blocking queue. This means that if you call the take () method to get the queue while the queue is empty, the worker thread will wait for any item to be added to the queue automatically.

So:

  • You cannot pause execution; this will complicate your code.
  • The blocking queue is executed by design exactly what you need: blocking the task if the queue is empty.
  • if you prefer, you can simply run the task periodically and check if queue isEmpty.
  • You should already use one way or another in your task anyway otherwise you would have a NullPointerException when the queue is empty.
+3
source share

You can do

 if(!queue.isEmpty()) return; 

at the beginning.

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

+3
source share

All Articles