Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of Java's ScheduledExecutorService.scheduleAtFixedRate()

I have a question regarding the scheduleAtFixedRate() method on ScheduledExecutorService in Java 6.

[edit: the Javadoc for 1.6 is more complete than that for 1.5. See comment below]

Given that:

  • the ScheduledExecutorService is constructed with N = 1 thread in the pool
  • the fixed-rate is a period of T seconds
  • no initial delay

What happens in this case (times are not meant to be absolute, in the real-time sense):

  • at time T, the service kicks off a Runnable task, "task1"
  • at time 2T, task1 has not yet completed, and service is scheduled to fire

Is the service guaranteed to do any of the following?

  • (a) at 2T, kick off a Runnable task, "task2" (recall N = 1)
  • (b) block until task1 is finished
  • (c) skip this time and try again at 3T
  • (d) behavior is undefined

Or something else? Does the answer change if N > 1 ?

like image 958
Michael Easter Avatar asked Jan 16 '12 22:01

Michael Easter


2 Answers

The answer is

(b) block until task1 is finished

and that is regardless of number of threads of the executor (task2 might even be not submitted).

The doc says:

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

(BTW, since there's no intial delay, "task1" will kickoff right away as doc`ed:

executions will commence after initialDelay

).

like image 79
yair Avatar answered Oct 12 '22 19:10

yair


From the documentation that you linked...

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

like image 34
kabuko Avatar answered Oct 12 '22 20:10

kabuko