Path: blob/master/test/hotspot/jtreg/runtime/HiddenClasses/GCHiddenClass.java
40942 views
/*1* Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/*24* @test25* @summary Test that hidden classes get garbage collected.26* @library /test/lib27* @modules jdk.compiler28* @run main GCHiddenClass29*/303132import java.lang.invoke.MethodType;33import java.lang.invoke.MethodHandles;34import java.lang.invoke.MethodHandles.Lookup;35import java.lang.ref.PhantomReference;36import java.lang.ref.Reference;37import java.lang.ref.ReferenceQueue;3839import static java.lang.invoke.MethodHandles.Lookup.ClassOption.*;40import jdk.test.lib.compiler.InMemoryJavaCompiler;4142public class GCHiddenClass {4344static byte klassbuf[] = InMemoryJavaCompiler.compile("TestClass",45"public class TestClass { " +46" public TestClass() { " +47" System.out.println(\"Hello\"); " +48" } } ");4950// A private method is great to keep hidden Class reference local to make it51// GCed on the next cycle52private PhantomReference<Class<?>> createClass(ReferenceQueue<Class<?>> refQueue) throws Exception {53Lookup lookup = MethodHandles.lookup();54Class<?> cl = lookup.defineHiddenClass(klassbuf, false, NESTMATE).lookupClass();55return new PhantomReference<Class<?>>(cl, refQueue);56}5758public boolean run() throws Exception {59ReferenceQueue<Class<?>> refQueue = new ReferenceQueue<Class<?>>();60PhantomReference<Class<?>> hiddenClassRef = createClass(refQueue);61System.gc();62Reference<? extends Class<?>> deletedObject = refQueue.remove();63return hiddenClassRef.equals(deletedObject);64}6566public static void main(String[] args) throws Throwable {67GCHiddenClass gcHC = new GCHiddenClass();68if (!gcHC.run()) {69throw new RuntimeException("Test failed");70}71}72}737475