jn1kk
jn1kk

Reputation: 5112

Executor Service and scheduleWithFixedDelay()

Here is my task. I have a static queue of jobs in a class and a static method that adds jobs to the queue. Have n amount of threads that poll from a queue and perform the pulled job. I need to have the n threads poll simultaneously at an interval. AKA, all 3 should poll every 5 seconds and look for jobs.

I have this:

public class Handler {

    private static final Queue<Job> queue = new LinkedList<>();

    public static void initialize(int maxThreads) { // maxThreads == 3

        ScheduledExecutorService executorService =
            Executors.newScheduledThreadPool(maxThreads);

        executorService.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                Job job = null;
                synchronized(queue) {
                    if(queue.size() > 0) {
                        job = queue.poll();
                    }
                }
                if(job != null) {
                    Log.log("start job");
                    doJob(job);
                    Log.log("end job");
                }
            }    
        }, 15, 5, TimeUnit.SECONDS);

    }

}

I get this output when I add 4 tasks:

startjob
endjob
startjob
endjob
startjob
endjob
startjob
endjob

It is obvious that these threads perform that jobs serially, whereas I need them to be done 3 at a time. What am I doing wrong? Thanks!

Upvotes: 1

Views: 3076

Answers (3)

TwoThe
TwoThe

Reputation: 14309

If you declare Job extends Runnable then your code simplifies dramatically:

First declare the Executor somewhere globally accessible:

public static final ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS);

Then add a job like this:

executor.submit(new Job());

You are done.

Upvotes: 0

Veaceslav Gaidarji
Veaceslav Gaidarji

Reputation: 4311

You are running ScheduledExecutorService with fixed delay, what means, that your jobs will run one after one. Use fixed thread pool, and submit 3 threads at a time. Here is an explanation with examples

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200296

From the documentation:

If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

So you must schedule three independent tasks to have them run concurrently. Also note that the scheduled executor service is a fixed thread pool, which is not flexible enough for many use cases. A good idiom is to use the scheduled service just to submit tasks to a regular executor service, which may be configured as a resizable thread pool.

Upvotes: 2

Related Questions