The articles on the site related to Timer talk about how to use Timer to program.
I ask a different question. How does Java perform Timer method?
Since it is said to avoid time-consuming work by not to use while loop to check whether the current time is the required time point, I think Timer is not implemented simply by using while loop to continuously checking and comparing the current time to the desired time point.
Thank you!
A Timer in Java is a process that enables threads to schedule tasks for later execution. Scheduling is done by keeping a specific process in the queue such that when the execution time comes, the processor can suspend other processes and run the task.
A Java. util. Timer is a utility class used to schedule a task to be executed after a specific amount of time. Tasks can be scheduled for one-time execution or for repeated execution periodically.
The java. util. Timer class provides facility for threads to schedule tasks for future execution in a background thread. This class is thread-safe i.e multiple threads can share a single Timer object without the need for external synchronization.
I think Timer is not implemented simply by using while loop to continuously checking and comparing the current time to the desired time point.
YES, IT IS. The only optimization is; it is using priority queue based on nextExecutionTime for tasks.
JavaDoc states
Timer object is a single background thread that is used to execute all of the timer's tasks, sequentially. Timer tasks should complete quickly. If a timer task takes excessive time to complete, it "hogs" the timer's task execution thread. This can, in turn, delay the execution of subsequent tasks
Timer class contains
TaskQueue
which is a priority queue of TimerTasks, ordered on nextExecutionTime.TimerThread(queue)
the timer's task execution thread, which waits (queue.wait()
) for tasks on the timer queue.TimerThread
has private void mainLoop() {
where continuous while(true)
will keep checking the tasks by comparing nextExecutionTime
with currentTimeMillis
currentTime = System.currentTimeMillis();
executionTime = task.nextExecutionTime;
if (taskFired = (executionTime<=currentTime)) {
and if it reaches then calling
if (taskFired) // Task fired; run it, holding no locks
task.run();
According for the javadoc
This class does not offer real-time guarantees: it schedules tasks using the Object.wait(long) method.
If you look in the code you will find a method called main loop. The first couple of lines are copied below.
private void mainLoop() {
while (true) {
try {
And... it uses a while loop inside of it along with Object.wait()
to do the waiting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With