Java – How to Pause ScheduledExecutorService for Scheduled Tasks

executorjavascheduled-tasks

I am using a ScheduledExecutorService to execute a task that calls a service at a fixed rate. The service may return some data to the task. The task stores data in a queue. Some other threads slowly pick 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 do I pause the executorService until the queue populated by the task has been cleared.

Best Answer

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?

Related Question