Java.util.Timer is a class for dispatching the background mission. Timertask is a task. Which use a balanced binary heap algorithm: / ** * This class represents a timer task queue:. A priority queue of TimerTasks, * ordered on nextExecutionTime Each Timer object has one of these, which it * shares with its TimerThread Internally. this class uses a heap, which * offers log (n) performance for the add, removeMin and rescheduleMin * operations, and constant time performance for the the getMin operation. * / class TaskQueue {/ ** * Priority queue represented as a balanced binary heap: the two children * of queue [n] are queue [2 * n] and queue [2 * n 1] The priority queue is * ordered on the nextExecutionTime field:. The TimerTask with the lowest * nextExecutionTime is in queue [ 1] (Assuming the Queue Is Nonempty). For * Each Node N in The Heap, And Each Descendant of N, D, * N.NexTexecutionTime <= D. NextexecutionTime. * / Private Timertask [] Queue = New Timertask [128] ;
/ ** * The Number of Tasks in the priority queue. (The Tasks Are Stored in * Queue [1] Up to queue [size]). * / Private int size = 0;
/ ** * Adds a new task to the priority queue. * / Void address {// grow backing store if Necessary if ( size == queue.length) {Timertask [] newqueue = new Timertask [2 * Queue.Length]; System.Arraycopy (Queue, 0, NewQueue, 0, size); Queue = Newqueue;}
Queue [SIZE] = TASK; fixup (size);
/ ** * Return the "Head task" of the priority Queue. ({Return Queue [1];}
/ ** * Remove The Head Task from the priority queue. * / Void Removemin () {queue [1] = queue [size]; queue [size--] = null; // drop extra reasonence to Prevent Memory Leak fixdown 1);.} / ** * Sets the nextExecutionTime associated with the head task to the * specified value, and adjusts priority queue accordingly * / void rescheduleMin (long newTime) {queue [1] .nextExecutionTime = newTime; fixDown (1) }
/ ** * Returns True if the priority queue Contains no elements. * / Boolean iSempty () {returnize == 0;
/ ** * Removes All Elements from the priority () {// null out task references to prevent memory leak for (int i = 1; i <= size; i ) Queue [i] = null;
SIZE = 0;}
/ ** * Establishes the heap invariant (described above) assuming the heap * satisfies the invariant except possibly for the leaf-node indexed by k * (which may have a nextExecutionTime less than its parent's). * * This method functions by "promoting "queue [k] up the hierarchy * (by swapping it with its parent) repeatedly until queue [k] 's * nextExecutionTime is greater than or equal to that of its parent. * / private void fixUp (int k) {while ( K> 1) {INT J = K >> 1; if (Queue [J] .NexTexecutionTime <= queue [k] .nextexecutionTIME) Break; timertask tmp = queue [j]; queue [j] = queueueue [k]; Queue [k] = TMP; k = j;}}