Maxsteel
Maxsteel

Reputation: 2040

ScheduledExecutorService not creating concurrent threads

I am trying to understand how ScheduledExecutorService works. I wrote this simple test:

ScheduledExecutorService executorService = Executors.newScheduledThreadPool(10);
    executorService.scheduleAtFixedRate(() -> {
      try {
        System.out.println("Test " + Thread.currentThread().getId());
        Thread.sleep(10000);
        System.out.println("End  " + Thread.currentThread().getId());
      } catch (Exception ex) {

      }
    }, 0, 100, TimeUnit.MILLISECONDS);

I see following printed on console:

Test 19
End  19
Test 19
End  19
Test 21
End  21

And so on. Shouldn't the executor schedule and start a new thread even before first thread ends? Why are threads started one after the other if core pool size is 10. shouldn't 10 threads run together.

Upvotes: 1

Views: 638

Answers (1)

IronMan
IronMan

Reputation: 1960

A recurring task is non-overlapping, so the first invocation would need to finish before the next can start:

Successive executions of a task scheduled via scheduleAtFixedRate or scheduleWithFixedDelay do not overlap. While different executions may be performed by different threads, the effects of prior executions happen-before those of subsequent ones.

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

https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html#scheduleAtFixedRate-java.lang.Runnable-long-long-java.util.concurrent.TimeUnit-

Upvotes: 7

Related Questions