Question

I know that I must use this instead of java.util.Timer because of various reasons. So, to study this I was looking at the docs and I have a few questions:

  1. How does scheduleWithFixedDelay() work ? My understanding is this: It first executes a task after a given delay. Once the task is done, it waits for the specified time and then executes the task again.
  2. What happens when I submit a task to scheduleAtFixedRate() that takes a lot more time to execute than the specified delay ? Like I want the task to execute every 5 seconds but it takes 10 seconds to complete. My understanding is that the task will be held in a queue and will be executed once a core thread is available
  3. Here is my understanding of how scheduleWithFixedDelay() and scheduleAtFixedRate() differ: scheduleWithFixedDelay() waits for the task to finish executing, waits for the specified time and then fires the task again where as scheduleAtFixedRate will just keep firing the task without caring if it has completed or not. Correct?
Was it helpful?

Solution

  1. Correct.
  2. Not quite. If a fixed-rate task takes longer than its period, it will run again immediately upon completion, but the next run is not waiting for a thread. See below.
  3. A fixed-rate task does care whether its previous run has completed, just like a fixed-delay task. Per the documentation, "If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute."

Think of it this way:

  • For a fixed-delay task, you specify a period which will be the exact amount of time between runs. The actual duration of the task has no effect on the delay.
  • For a fixed-rate task, you specify a period which will be the maximum amount of time between runs. If the actual duration of the task is longer than the period, the rate is reduced, and there is effectively no delay.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top