Ted
Ted

Reputation: 1690

ScheduledExecutorService only calling one thread

I want to pull multiple files from a queue and parse them simultaneously. However, my executor is only calling one thread:

private static ScheduledExecutorService parsingExec ;
protected static BlockingQueue<Path> queue = new LinkedBlockingQueue<>();
int threadPoolSize = 10;
parsingExec = Executors.newScheduledThreadPool(threadPoolSize);
parsingExec.scheduleAtFixedRate(new MyParser(queue), 0, 0, TimeUnit.MILLISECONDS);

Upvotes: 0

Views: 2226

Answers (2)

Simulant
Simulant

Reputation: 20140

parsingExec.scheduleAtFixedRate(new MyParser(queue), 0, 1, TimeUnit.MILLISECONDS);

This line schedules one Runnable. You have to call this line once for every Thread you want do schedule simultaniusly. I think you should split up the queue and give the splitted parts to your Constructor, and schedule them once for every part. Also scheduleAtFixedRate repeates the job forever, I think you don't want this behavior. If you want to execute this just once use submit instead:

//split the queue in parts before
for(int i = 0; i < numberOfQueueParts; i++) {
    parsingExec.submit(new MyParser(queuePart));
}

Upvotes: 0

Perception
Perception

Reputation: 80633

From the Javadoc for scheduleWithFixedRate():

Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on. If any execution of the task encounters an exception, subsequent executions are suppressed. Otherwise, the task will only terminate via cancellation or termination of the executor. If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.

This method is for scheduling a single task, to be executed multiple times. The key thing to note being that only one instance of your task will ever be executing at a time. If you want to execute multiple tasks simultaneously then you should be using, for example, a fixed thread pool instead.

final ExecutorService parsingExec = Executors.newFixedThreadPool(threadPoolSize);
for(final int i = 0; i < threadPoolSize; i++) {
    parsingExec.submit(new MyParser(queue));
}

Upvotes: 9

Related Questions