RFR: 8263903: Use Cleaner instead of finalize to auto stop Timer thread

Kim Barrett kbarrett at openjdk.java.net
Mon Mar 22 05:39:42 UTC 2021


On Sun, 21 Mar 2021 22:49:37 GMT, David Holmes <dholmes at openjdk.org> wrote:

>> Please review this change to java.util.Timer, replacing the use of deprecated finalization-based cleanup with use of java.lang.ref.Cleaner.
>> 
>> In addition, Timer.cancel now cancels any later execution of the the no longer relevant cleanup.
>> 
>> Testing:
>> mach5 tier1
>> New AutoStop test verifies the specified cleanup behavior.
>> (There are existing tests involving Timer.cancel.)
>
> test/jdk/java/util/Timer/AutoStop.java line 67:
> 
>> 65:             t.schedule(new TimerTask() {
>> 66:                     public void run() {
>> 67:                         ++counter;
> 
> This is not thread-safe. Operations on volatile variables are not atomic.

Only one thread (the timer's thread) is writing, via a sequential series of task executions, so the simple increments are fine.  I made `counter` volatile because it's being written by one thread and read by a different thread.  Happy to drop the qualifier if that's not needed.

-------------

PR: https://git.openjdk.java.net/jdk/pull/3106


More information about the core-libs-dev mailing list