JDK-8319378 : Spec for j.util.Timer::purge and j.util.Timer::cancel could be improved
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.util
  • Priority: P4
  • Status: Resolved
  • Resolution: Fixed
  • Submitted: 2023-11-03
  • Updated: 2023-12-08
  • Resolved: 2023-11-07
The Version table provides details related to the release that this issue/RFE will be addressed.

Unresolved : Release in which this issue/RFE will be addressed.
Resolved: Release in which this issue/RFE has been resolved.
Fixed : Release in which this issue/RFE has been fixed. The release containing this fix may be available for download as an Early Access Release or a General Availability Release.

To download the current JDK release, click here.
JDK 22
22 b23Fixed
Related Reports
CSR :  
Relates :  
Description
The spec for j.u.Timer::purge asserts:

================
Removes all cancelled tasks from this timer's task queue. 
Calling this method has no effect on the behavior of the timer, but eliminates the references to the cancelled tasks from the queue.

Returns:
the number of tasks removed from the queue
================

However the OpenJDK implementation seem to be not completely matching the spec and the following example

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override public void run() { System.out.println("timer = " + timer); }
        }, 5000);
        timer.cancel();
        System.out.println("timer.purge() = " + timer.purge());


prints

    timer.purge() = 0

consistently



Comments
Changeset: cc4b0d92 Author: Justin Lu <jlu@openjdk.org> Date: 2023-11-07 21:33:33 +0000 URL: https://git.openjdk.org/jdk/commit/cc4b0d9217ed27a9555dc82f0a4247bf9b703f2b
07-11-2023

A pull request was submitted for review. URL: https://git.openjdk.org/jdk/pull/16503 Date: 2023-11-03 20:40:11 +0000
03-11-2023

FWIW, Timer.cancel discards the scheduled tasks, it does not cancel them. In order to get a non-zero number from purge, you need to cancel the task itself, for example: Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { System.out.println("timer = " + timer); } }; timer.schedule(task, 5000); task.cancel(); System.out.println("timer.purge() = " + timer.purge()); prints: timer.purge() = 1
03-11-2023