
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Cancelled Tasks from 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
Advertisements