1 /* 2 * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 */ 23 24 /* 25 * @test 26 * @bug 8263903 27 * @requires vm.gc != "Epsilon" 28 * @summary Discarding a Timer causes the Timer thread to stop. 29 */ 30 31 package test.java.util.Timer; 32 33 import java.util.Timer; 34 import java.util.TimerTask; 35 import java.lang.ref.Reference; 36 37 public class AutoStop { 38 static final Object wakeup = new Object(); 39 static Thread tdThread = null; 40 static volatile int counter = 0; 41 static final int COUNTER_LIMIT = 10; 42 main(String[] args)43 public static void main(String[] args) throws Exception { 44 Timer t = new Timer(); 45 46 // Run an event that records the timer thread. 47 t.schedule(new TimerTask() { 48 public void run() { 49 synchronized(wakeup) { 50 tdThread = Thread.currentThread(); 51 wakeup.notify(); 52 } 53 } 54 }, 0); 55 56 // Wait for the thread to be accessible. 57 try { 58 synchronized(wakeup) { 59 while (tdThread == null) { 60 wakeup.wait(); 61 } 62 } 63 } catch (InterruptedException e) { 64 } 65 66 // Schedule some events that increment the counter. 67 for (int i = 0; i < COUNTER_LIMIT; ++i) { 68 t.schedule(new TimerTask() { 69 public void run() { 70 ++counter; 71 } 72 }, 100); 73 } 74 75 // Ensure the timer is accessible at least until here. 76 Reference.reachabilityFence(t); 77 t = null; // Remove the reference to the timer. 78 // Android-changed: on sunfish this test run drops from 30s to 80ms 79 // System.gc(); // Run GC to trigger cleanup. 80 for (int i = 0; i < 5; ++i) { 81 Runtime.getRuntime().gc(); 82 } 83 tdThread.join(); // Wait for thread to stop. 84 int finalCounter = counter; 85 if (finalCounter != COUNTER_LIMIT) { 86 throw new RuntimeException("Unrun events: counter = " + finalCounter); 87 } 88 } 89 } 90 91