Reputation: 2389
I'm reading a java8 book and come across the difference between scheduleAtFixedRate
and scheduleWithFixedDelay
methods from ScheduledExecutorService
.
I understand the difference between these two methods on the book, however when I tried to write a simple code. It's not so clear why scheduleAtFixedRate
behaves synchronously.
As you can see, I'm allocating 100 threads in the pool. And the scheduler will submit a new task every 1ms, and per task, there's a delay of 1s.
ScheduledExecutorService s = Executors.newScheduledThreadPool(100);
s.scheduleAtFixedRate(() -> {
int num = new Random().nextInt(100);
System.out.println("Hello World" + num);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Finished" + num);
}, 0, 1, TimeUnit.MILLISECONDS);
But why am I getting this output ? A new task will run only after the other.
Hello World94
Finished94
Hello World14
Finished14
Hello World90
Finished90
Hello World26
Finished26
Upvotes: 4
Views: 3995
Reputation: 21975
Take a look at the javadoc for ScheduledThreadPoolExecutor#scheduleAtFixedRate
If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute.
So do not await for it to execute concurrently, it will always execute sequentially..
Upvotes: 6