/* * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.internal.ref; import jdk.internal.misc.InnocuousThread; import jdk.internal.misc.JavaLangRefAccess; import jdk.internal.misc.SharedSecrets; import java.lang.ref.Cleaner; import java.lang.ref.ReferenceQueue; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Objects; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.StampedLock; import java.util.function.BooleanSupplier; /** * CleanerImpl is the implementation of {@link Cleaner}. */ public class CleanerImpl implements Cleaner { final Task task; public CleanerImpl(ThreadFactory threadFactory) { task = new Task(); task.start(this, threadFactory); } @Override public Cleanable register(Object obj, Runnable action) { Objects.requireNonNull(obj, "obj"); Objects.requireNonNull(action, "action"); return new CleanerImpl.PhantomCleanableRef(obj, this, action); } /** * CleanerImpl.ExtendedImpl is the implementation of {@link ExtendedCleaner}. */ static class ExtendedImpl extends CleanerImpl implements ExtendedCleaner { ExtendedImpl(ThreadFactory threadFactory) { super(threadFactory); } // A fair lock for threads that retry operations to queue after // 1st optimistic try fails so that only a single thread at a time is // retrying operations while helping the Cleaner execute Cleanable(s) // and trigger new Reference discovery before finally giving up. private final StampedLock helpingLock = new StampedLock(); public boolean retryWhileHelpingClean(BooleanSupplier retriableOperation) { // 1st optimistic try - allow concurrent execution of operations // until helping is necessary long stamp = helpingLock.tryReadLock(); if (stamp != 0) try { if (retriableOperation.getAsBoolean()) { return true; } } finally { helpingLock.unlockRead(stamp); } // retrials with helping is exclusive stamp = helpingLock.writeLock(); try { // retry operation while executing enqueued Cleanable(s) until the // queue drains out do { if (retriableOperation.getAsBoolean()) { return true; } } while (task.cleanNextEnqueued()); JavaLangRefAccess jlra = SharedSecrets.getJavaLangRefAccess(); // trigger Reference(s) discovery int discoveryPhase = jlra.discoverReferences(); // wait for newly discovered Reference(s) to be enqueued boolean interrupted = false; try { while (true) { try { jlra.awaitReferencesEnqueued(discoveryPhase); break; } catch (InterruptedException e) { // ignore interrupts but don't swallow them interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } // the queue is now hopefully filled with new pending Cleanable(s) // so retry operation while executing enqueued Cleanable(s) until the // queue drains out do { if (retriableOperation.getAsBoolean()) { return true; } } while (task.cleanNextEnqueued()); // give up finally return false; } finally { helpingLock.unlockWrite(stamp); } } } // package-private access to Task's state PhantomCleanable phantomCleanableList() { return task.phantomCleanableList; } WeakCleanable weakCleanableList() { return task.weakCleanableList; } SoftCleanable softCleanableList() { return task.softCleanableList; } ReferenceQueue queue() { return task.queue; } /** * CleanerImpl.Task manages a set of object references and corresponding * cleaning actions and executes them after they are enqueued. */ private static final class Task implements Runnable { /** * Heads of a CleanableList for each reference type. */ final PhantomCleanable phantomCleanableList; final WeakCleanable weakCleanableList; final SoftCleanable softCleanableList; // The ReferenceQueue of pending cleaning actions final ReferenceQueue queue; /** * Constructor for Task. */ Task() { queue = new ReferenceQueue<>(); phantomCleanableList = new PhantomCleanableRef(); weakCleanableList = new WeakCleanableRef(); softCleanableList = new SoftCleanableRef(); } /** * Starts the Cleaner implementation. * Ensure this is the CleanerImpl for the Cleaner. * When started waits for Cleanables to be queued. * @param cleaner the cleaner * @param threadFactory the thread factory */ void start(CleanerImpl cleaner, ThreadFactory threadFactory) { if (cleaner.task != this) { throw new AssertionError("wrong cleaner"); } // schedule a nop cleaning action for the cleaner, so the associated thread // will continue to run at least until the cleaner is reclaimable. new CleanerCleanable(cleaner); if (threadFactory == null) { threadFactory = CleanerImpl.InnocuousThreadFactory.factory(); } // now that there's at least one cleaning action, for the cleaner, // we can start the associated thread, which runs until // all cleaning actions have been run. Thread thread = threadFactory.newThread(this); thread.setDaemon(true); thread.start(); } /** * Process queued Cleanables as long as the cleanable lists are not empty. * A Cleanable is in one of the lists for each Object and for the Cleaner * itself. * Terminates when the Cleaner is no longer reachable and * has been cleaned and there are no more Cleanable instances * for which the object is reachable. *

* If the thread is a ManagedLocalsThread, the threadlocals * are erased before each cleanup */ @Override public void run() { Thread t = Thread.currentThread(); InnocuousThread mlThread = (t instanceof InnocuousThread) ? (InnocuousThread) t : null; while (!phantomCleanableList.isListEmpty() || !weakCleanableList.isListEmpty() || !softCleanableList.isListEmpty()) { if (mlThread != null) { // Clear the thread locals mlThread.eraseThreadLocals(); } try { // Wait for a Ref, with a timeout to avoid getting hung // due to a race with clear/clean Cleanable ref = (Cleanable) queue.remove(60 * 1000L); if (ref != null) { ref.clean(); } } catch (Throwable e) { // ignore exceptions from the cleanup action // (including interruption of cleanup thread) } } } /** * Processes next Cleanable that has been waiting in the queue. * * @return {@code true} if a Cleanable was found in the queue and * was processed or {@code false} if the queue was empty. */ boolean cleanNextEnqueued() { Cleanable ref = (Cleanable) queue.poll(); if (ref != null) { try { ref.clean(); } catch (Throwable t) { // ignore exceptions from the cleanup action } return true; } else { return false; } } } /** * Perform cleaning on an unreachable PhantomReference. */ public static final class PhantomCleanableRef extends PhantomCleanable { private final Runnable action; /** * Constructor for a phantom cleanable reference. * @param obj the object to monitor * @param cleaner the cleaner * @param action the action Runnable */ public PhantomCleanableRef(Object obj, Cleaner cleaner, Runnable action) { super(obj, cleaner); this.action = action; } /** * Constructor used only for root of phantom cleanable list. */ PhantomCleanableRef() { super(); this.action = null; } @Override protected void performCleanup() { action.run(); } /** * Prevent access to referent even when it is still alive. * * @throws UnsupportedOperationException always */ @Override public Object get() { throw new UnsupportedOperationException("get"); } /** * Direct clearing of the referent is not supported. * * @throws UnsupportedOperationException always */ @Override public void clear() { throw new UnsupportedOperationException("clear"); } } /** * Perform cleaning on an unreachable WeakReference. */ public static final class WeakCleanableRef extends WeakCleanable { private final Runnable action; /** * Constructor for a weak cleanable reference. * @param obj the object to monitor * @param cleaner the cleaner * @param action the action Runnable */ WeakCleanableRef(Object obj, Cleaner cleaner, Runnable action) { super(obj, cleaner); this.action = action; } /** * Constructor used only for root of weak cleanable list. */ WeakCleanableRef() { super(); this.action = null; } @Override protected void performCleanup() { action.run(); } /** * Prevent access to referent even when it is still alive. * * @throws UnsupportedOperationException always */ @Override public Object get() { throw new UnsupportedOperationException("get"); } /** * Direct clearing of the referent is not supported. * * @throws UnsupportedOperationException always */ @Override public void clear() { throw new UnsupportedOperationException("clear"); } } /** * Perform cleaning on an unreachable SoftReference. */ public static final class SoftCleanableRef extends SoftCleanable { private final Runnable action; /** * Constructor for a soft cleanable reference. * @param obj the object to monitor * @param cleaner the cleaner * @param action the action Runnable */ SoftCleanableRef(Object obj, Cleaner cleaner, Runnable action) { super(obj, cleaner); this.action = action; } /** * Constructor used only for root of soft cleanable list. */ SoftCleanableRef() { super(); this.action = null; } @Override protected void performCleanup() { action.run(); } /** * Prevent access to referent even when it is still alive. * * @throws UnsupportedOperationException always */ @Override public Object get() { throw new UnsupportedOperationException("get"); } /** * Direct clearing of the referent is not supported. * * @throws UnsupportedOperationException always */ @Override public void clear() { throw new UnsupportedOperationException("clear"); } } /** * A ThreadFactory for InnocuousThreads. * The factory is a singleton. */ static final class InnocuousThreadFactory implements ThreadFactory { final static ThreadFactory factory = new InnocuousThreadFactory(); static ThreadFactory factory() { return factory; } final AtomicInteger cleanerThreadNumber = new AtomicInteger(); public Thread newThread(Runnable r) { return AccessController.doPrivileged(new PrivilegedAction<>() { @Override public Thread run() { Thread t = InnocuousThread.newThread(r); t.setPriority(Thread.MAX_PRIORITY - 2); t.setName("Cleaner-" + cleanerThreadNumber.getAndIncrement()); return t; } }); } } /** * A PhantomCleanable implementation for tracking the Cleaner itself. */ static final class CleanerCleanable extends PhantomCleanable { CleanerCleanable(Cleaner cleaner) { super(cleaner, cleaner); } @Override protected void performCleanup() { // no action } } }