Remove all cancelled tasks from the timer's task queue in Java


One of the methods of the Timer class is the int purge() method. The purge() method removes all the canceled tasks from the timer’s task queue. Invoking this method does not affect the behavior of the timer, rather it eliminates references to the canceled tasks from the queue. The purge() method came into existence since JDK 1.5.

The purge() method acts as a medium for space-time tradeoff where it trades time for space. More specifically, the time complexity of the method is proportional to n + c log n, where n is the number of tasks in the queue and c is the number of canceled tasks.

Declaration −The java.util.Timer.purge() method is declared as follows −

public int purge()

Let us see an example program of the purge() method

Example

import java.util.*;
public class Example {
   public static void main(String[] args) {
      Timer timer = new Timer(); // creating timer
      TimerTask task = new TimerTask() // creating timer task {
      public void run() {
         for(int i=1; i<=5;i++) {
            System.out.println("Task is running");
               if(i>=3) {
                  System.out.println("Task terminated");
                  timer.cancel();
                  break;
               }
            }
            // printing the purge value of the task by purging the timer
            System.out.println("The purge of the task is "+timer.purge());
         };
      };
      timer.schedule(task,7000,4000);
   }
}

Output

Task is running
Task is running
Task is running
Task terminated
The purge of the task is 0

Updated on: 26-Jun-2020

248 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements