Path: blob/master/test/hotspot/jtreg/vmTestbase/gc/g1/unloading/keepref/NullClassloaderHolder.java
41161 views
/*1* Copyright (c) 2014, 2020, 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*/22package gc.g1.unloading.keepref;2324import java.lang.reflect.*;25import java.util.*;2627/**28* This holder keeps class from being collected by saving link in static field of class loaded by null classloader.29* It uses pool of classes that should reside in bootclasspath.30*/31public class NullClassloaderHolder implements RefHolder {3233private static final int NUMBER_OF_CLASSES = 1000;34private static Set<Class<?>> classesPool = Collections.synchronizedSet(new HashSet<Class<?>>());35private final Random random;3637static {38for (int i = 1; i <= NUMBER_OF_CLASSES; i++) {39String className = "gc.g1.unloading.rootSetHelper.classesPool.Class" + i;40try {41Class<?> clazz = Class.forName(className);42if (clazz.getClassLoader() != null) {43throw new RuntimeException("Test bug! Classes from pool implied to be loaded by bootclassloader.");44}45classesPool.add(clazz);46} catch (ClassNotFoundException e) {47throw new RuntimeException("Test bug", e);48}49}50}5152public NullClassloaderHolder(long seed) {53random = new Random(seed);54}5556@Override57public Object hold(Object object) {58if (classesPool.isEmpty()) {59return null;60} else {61Class<?> clazz = (Class<?>) classesPool.iterator().next();62classesPool.remove(clazz);63Field f = getRandomField(clazz);64try {65f.set(null, object);66return clazz.newInstance();67} catch (IllegalArgumentException | IllegalAccessException | InstantiationException e) {68throw new RuntimeException("Test bug", e);69}70}71}7273private Field getRandomField(Class<?> clazz) {74ArrayList<Field> fields = new ArrayList<>();75for (Field f : clazz.getFields()) {76if (f.getName().startsWith("staticField")) {77fields.add(f);78}79}80return fields.get(random.nextInt(fields.size()));81}8283}848586