1 /*
 2  * Copyright (c) 2019, 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  * @summary Test that virtual threads are GC'ed
27  * @compile --enable-preview -source ${jdk.version} Collectable.java
28  * @run testng/othervm --enable-preview Collectable
29  */
30 
31 import java.lang.ref.WeakReference;
32 import java.util.concurrent.locks.LockSupport;
33 
34 import org.testng.annotations.Test;
35 import static org.testng.Assert.*;
36 
37 public class Collectable {
38 
39     /**
40      * Test that an unstarted virtual thread can be GC"ed.
41      */
42     @Test
43     public void testUnstartedThread() {
44         var thread = Thread.ofVirtual().unstarted(() -> { });
45         var ref = new WeakReference<>(thread);
46         thread = null;
47         waitUntilCleared(ref);
48     }
49 
50     /**
51      * Test that a parked virtual thread can be GC'ed.
52      */
53     @Test
54     public void testParkedThread() {
55         var thread = Thread.ofVirtual().start(LockSupport::park);
56         var ref = new WeakReference<>(thread);
57         thread = null;
58         waitUntilCleared(ref);
59     }
60 
61     /**
62      * Ensure that a terminated virtual thread can be GC'ed.
63      */
64     @Test
65     public void testTerminatedThread() throws Exception {
66         var thread = Thread.ofVirtual().start(() -> { });
67         thread.join();
68         var ref = new WeakReference<>(thread);
69         thread = null;
70         waitUntilCleared(ref);
71     }
72 
73     private static void waitUntilCleared(WeakReference<?> ref) {
74         while (ref.get() != null) {
75             System.gc();
76             try {
77                 Thread.sleep(50);
78             } catch (InterruptedException ignore) { }
79         }
80     }
81 }