How is Java Timer implemented on a computer?

The articles on the website related to the timer talk about how to use the timer for programming.

I ask another question. How does Java execute the Timer method?

Since, as they say, in order to avoid time-consuming work, not to use the while loop to check whether the current time is the required time, I think the timer is not implemented simply by using the while loop to constantly check and compare the current time to the desired point time.

Thanks!

+7
source share
2 answers

I think the timer is not implemented simply, using a while loop to continuously check and compare the current time with the desired time point.

YES THIS. The only optimization; it uses a priority queue based on nextExecutionTime for tasks.

JavaDoc Status

A timer object is a single background thread that is used to perform all timer tasks in sequence. Timer tasks should complete quickly. If the timer task takes too long to complete, it starts the timer task execution thread. This may, in turn, delay the execution of subsequent tasks.

Timer class contains

  • TaskQueue , which is a priority queue of TimerTasks ordered in nextExecutionTime.
  • TimerThread(queue) timer task execution thread that waits for ( queue.wait() ) tasks in the timer queue.

TimerThread has private void mainLoop() {
where continuous while(true) will continue to check tasks by comparing nextExecutionTime with currentTimeMillis

  currentTime = System.currentTimeMillis(); executionTime = task.nextExecutionTime; if (taskFired = (executionTime<=currentTime)) { 

and if he reaches, then the challenge

  if (taskFired) // Task fired; run it, holding no locks task.run(); 
+2
source

According to 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 the main loop. The first two lines are copied below.

 private void mainLoop() { while (true) { try { 

And ... it uses the while loop inside it along with Object.wait() to wait.

+1
source

All Articles