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

Java 8Object Oriented ProgrammingProgramming

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
public void run() {
for(int i=1; i<=5;i++) {
if(i>=3) {
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());
};
};
}
Task is running
The purge of the task is 0