Path: blob/master/src/java.base/share/classes/jdk/internal/ref/CleanerImpl.java
41159 views
/*1* Copyright (c) 2015, 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. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package jdk.internal.ref;2627import java.lang.ref.Cleaner;28import java.lang.ref.Cleaner.Cleanable;29import java.lang.ref.ReferenceQueue;30import java.security.AccessController;31import java.security.PrivilegedAction;32import java.util.concurrent.ThreadFactory;33import java.util.concurrent.atomic.AtomicInteger;34import java.util.function.Function;3536import jdk.internal.misc.InnocuousThread;3738/**39* CleanerImpl manages a set of object references and corresponding cleaning actions.40* CleanerImpl provides the functionality of {@link java.lang.ref.Cleaner}.41*/42public final class CleanerImpl implements Runnable {4344/**45* An object to access the CleanerImpl from a Cleaner; set by Cleaner init.46*/47private static Function<Cleaner, CleanerImpl> cleanerImplAccess = null;4849/**50* Heads of a CleanableList for each reference type.51*/52final PhantomCleanable<?> phantomCleanableList;5354// The ReferenceQueue of pending cleaning actions55final ReferenceQueue<Object> queue;5657/**58* Called by Cleaner static initialization to provide the function59* to map from Cleaner to CleanerImpl.60* @param access a function to map from Cleaner to CleanerImpl61*/62public static void setCleanerImplAccess(Function<Cleaner, CleanerImpl> access) {63if (cleanerImplAccess == null) {64cleanerImplAccess = access;65} else {66throw new InternalError("cleanerImplAccess");67}68}6970/**71* Called to get the CleanerImpl for a Cleaner.72* @param cleaner the cleaner73* @return the corresponding CleanerImpl74*/75static CleanerImpl getCleanerImpl(Cleaner cleaner) {76return cleanerImplAccess.apply(cleaner);77}7879/**80* Constructor for CleanerImpl.81*/82public CleanerImpl() {83queue = new ReferenceQueue<>();84phantomCleanableList = new PhantomCleanableRef();85}8687/**88* Starts the Cleaner implementation.89* Ensure this is the CleanerImpl for the Cleaner.90* When started waits for Cleanables to be queued.91* @param cleaner the cleaner92* @param threadFactory the thread factory93*/94public void start(Cleaner cleaner, ThreadFactory threadFactory) {95if (getCleanerImpl(cleaner) != this) {96throw new AssertionError("wrong cleaner");97}98// schedule a nop cleaning action for the cleaner, so the associated thread99// will continue to run at least until the cleaner is reclaimable.100new CleanerCleanable(cleaner);101102if (threadFactory == null) {103threadFactory = CleanerImpl.InnocuousThreadFactory.factory();104}105106// now that there's at least one cleaning action, for the cleaner,107// we can start the associated thread, which runs until108// all cleaning actions have been run.109Thread thread = threadFactory.newThread(this);110thread.setDaemon(true);111thread.start();112}113114/**115* Process queued Cleanables as long as the cleanable lists are not empty.116* A Cleanable is in one of the lists for each Object and for the Cleaner117* itself.118* Terminates when the Cleaner is no longer reachable and119* has been cleaned and there are no more Cleanable instances120* for which the object is reachable.121* <p>122* If the thread is a ManagedLocalsThread, the threadlocals123* are erased before each cleanup124*/125@Override126public void run() {127Thread t = Thread.currentThread();128InnocuousThread mlThread = (t instanceof InnocuousThread)129? (InnocuousThread) t130: null;131while (!phantomCleanableList.isListEmpty()) {132if (mlThread != null) {133// Clear the thread locals134mlThread.eraseThreadLocals();135}136try {137// Wait for a Ref, with a timeout to avoid getting hung138// due to a race with clear/clean139Cleanable ref = (Cleanable) queue.remove(60 * 1000L);140if (ref != null) {141ref.clean();142}143} catch (Throwable e) {144// ignore exceptions from the cleanup action145// (including interruption of cleanup thread)146}147}148}149150/**151* Perform cleaning on an unreachable PhantomReference.152*/153public static final class PhantomCleanableRef extends PhantomCleanable<Object> {154private final Runnable action;155156/**157* Constructor for a phantom cleanable reference.158* @param obj the object to monitor159* @param cleaner the cleaner160* @param action the action Runnable161*/162public PhantomCleanableRef(Object obj, Cleaner cleaner, Runnable action) {163super(obj, cleaner);164this.action = action;165}166167/**168* Constructor used only for root of phantom cleanable list.169*/170PhantomCleanableRef() {171super();172this.action = null;173}174175@Override176protected void performCleanup() {177action.run();178}179180/**181* Prevent access to referent even when it is still alive.182*183* @throws UnsupportedOperationException always184*/185@Override186public Object get() {187throw new UnsupportedOperationException("get");188}189190/**191* Direct clearing of the referent is not supported.192*193* @throws UnsupportedOperationException always194*/195@Override196public void clear() {197throw new UnsupportedOperationException("clear");198}199}200201/**202* A ThreadFactory for InnocuousThreads.203* The factory is a singleton.204*/205static final class InnocuousThreadFactory implements ThreadFactory {206static final ThreadFactory factory = new InnocuousThreadFactory();207208static ThreadFactory factory() {209return factory;210}211212final AtomicInteger cleanerThreadNumber = new AtomicInteger();213214public Thread newThread(Runnable r) {215return InnocuousThread.newThread("Cleaner-" + cleanerThreadNumber.getAndIncrement(),216r, Thread.MIN_PRIORITY - 2);217}218}219220/**221* A PhantomCleanable implementation for tracking the Cleaner itself.222*/223static final class CleanerCleanable extends PhantomCleanable<Cleaner> {224CleanerCleanable(Cleaner cleaner) {225super(cleaner, cleaner);226}227228@Override229protected void performCleanup() {230// no action231}232}233}234235236