Skip to content
Permalink
Browse files
8263903: Use Cleaner instead of finalize to auto stop Timer thread
Reviewed-by: dholmes, alanb, bchristi, rriggs, mchung
  • Loading branch information
Kim Barrett committed Mar 23, 2021
1 parent 35102cb commit 2425462a84a619a4948fdf21fb2570595fe38797
Show file tree
Hide file tree
Showing 2 changed files with 108 additions and 14 deletions.
@@ -1,5 +1,5 @@
/*
* Copyright (c) 1999, 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,8 @@
package java.util;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import java.lang.ref.Cleaner.Cleanable;
import jdk.internal.ref.CleanerFactory;

/**
* A facility for threads to schedule tasks for future execution in a
@@ -101,21 +103,29 @@ public class Timer {
private final TimerThread thread = new TimerThread(queue);

/**
* This object causes the timer's task execution thread to exit
* gracefully when there are no live references to the Timer object and no
* tasks in the timer queue. It is used in preference to a finalizer on
* Timer as such a finalizer would be susceptible to a subclass's
* finalizer forgetting to call it.
* An object of this class is registered with a Cleaner as the cleanup
* handler for this Timer object. This causes the execution thread to
* exit gracefully when there are no live references to the Timer object
* and no tasks in the timer queue.
*/
private final Object threadReaper = new Object() {
@SuppressWarnings("deprecation")
protected void finalize() throws Throwable {
private static class ThreadReaper implements Runnable {
private final TaskQueue queue;
private final TimerThread thread;

ThreadReaper(TaskQueue queue, TimerThread thread) {
this.queue = queue;
this.thread = thread;
}

public void run() {
synchronized(queue) {
thread.newTasksMayBeScheduled = false;
queue.notify(); // In case queue is empty.
}
}
};
}

private final Cleanable cleanup;

/**
* This ID is used to generate thread names.
@@ -157,8 +167,7 @@ public Timer(boolean isDaemon) {
* @since 1.5
*/
public Timer(String name) {
thread.setName(name);
thread.start();
this(name, false);
}

/**
@@ -172,6 +181,8 @@ public Timer(String name) {
* @since 1.5
*/
public Timer(String name, boolean isDaemon) {
var threadReaper = new ThreadReaper(queue, thread);
this.cleanup = CleanerFactory.cleaner().register(this, threadReaper);
thread.setName(name);
thread.setDaemon(isDaemon);
thread.start();
@@ -428,9 +439,8 @@ private void sched(TimerTask task, long time, long period) {
*/
public void cancel() {
synchronized(queue) {
thread.newTasksMayBeScheduled = false;
queue.clear();
queue.notify(); // In case queue was already empty.
cleanup.clean();
}
}

@@ -0,0 +1,84 @@
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/

/*
* @test
* @bug 8263903
* @requires vm.gc != "Epsilon"
* @summary Discarding a Timer causes the Timer thread to stop.
*/

import java.util.Timer;
import java.util.TimerTask;
import java.lang.ref.Reference;

public class AutoStop {
static final Object wakeup = new Object();
static Thread tdThread = null;
static volatile int counter = 0;
static final int COUNTER_LIMIT = 10;

public static void main(String[] args) throws Exception {
Timer t = new Timer();

// Run an event that records the timer thread.
t.schedule(new TimerTask() {
public void run() {
synchronized(wakeup) {
tdThread = Thread.currentThread();
wakeup.notify();
}
}
}, 0);

// Wait for the thread to be accessible.
try {
synchronized(wakeup) {
while (tdThread == null) {
wakeup.wait();
}
}
} catch (InterruptedException e) {
}

// Schedule some events that increment the counter.
for (int i = 0; i < COUNTER_LIMIT; ++i) {
t.schedule(new TimerTask() {
public void run() {
++counter;
}
}, 100);
}

// Ensure the timer is accessible at least until here.
Reference.reachabilityFence(t);
t = null; // Remove the reference to the timer.
System.gc(); // Run GC to trigger cleanup.
tdThread.join(); // Wait for thread to stop.
int finalCounter = counter;
if (finalCounter != COUNTER_LIMIT) {
throw new RuntimeException("Unrun events: counter = " + finalCounter);
}
}
}

0 comments on commit 2425462

Please sign in to comment.