Search code examples
javatimertimeoutthreadpooljava-threads

What is pool size of timer.schedule() queue in java.util.Timer


How many tasks can be scheduled to call later on & is there any limit on that? I can't see any max limit specified anywhere. Example: Can I schedule 1000000 tasks to execute after 10 hour. I will be scheduling them just to give delay before execution of the tasks by adding them in queue.


Solution

  • In theory you can schedule an unlimited amount of TimerTasks - the Timer stores the tasks in a TimerTask array that is doubled in size if it fills up (https://github.com/AdoptOpenJDK/openjdk-jdk8u/blob/master/jdk/src/share/classes/java/util/Timer.java#L596).

    But note that a Timer uses only one background thread to execute all scheduled tasks (https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html):

    Corresponding to each Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially.

    So if you schedule thousands of tasks to run at the same time they are executed sequentially.


    Note that the thread is sleeping (not busy waiting until the next schedule time arrives). That means that a Timer with 1_000_000 TimerTasks scheduled in 10 hours won't need any CPU resources until the 10 hours have elapsed (it will use 1 Thread but that thread is blocked for those 10 hours, and it will necessarily require some memory to store references to those 1_000_000 TimerTask instances).

    This fact is also mentioned in the documentation:

    This class does not offer real-time guarantees: it schedules tasks using the Object.wait(long) method.

    Additional note: adding a TimerTask to a Timer necessarily wakes up the timer thread because the task that was just added could be the next to execute and therefore the timeout value for the Object.wait(long) method needs to be recomputed.

    Scheduling 1_000_000 TimerTasks will therefore necessarily wake up that thread up to 1_000_000 times (it can be less because it is possible that the task creating and adding TimerTask instance adds more than one TimerTask to the queue before the timer thread wakes up and inspects the queue).