/* * Copyright (c) 1997, 2013, 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 java.lang.ref; import sun.misc.Cleaner; import sun.misc.JavaLangRefAccess; import sun.misc.ManagedLocalsThread; import sun.misc.SharedSecrets; /** * Abstract base class for reference objects. This class defines the * operations common to all reference objects. Because reference objects are * implemented in close cooperation with the garbage collector, this class may * not be subclassed directly. * * @author Mark Reinhold * @since 1.2 */ public abstract class Reference { /* A Reference instance is in one of four possible internal states: * * Active: Subject to special treatment by the garbage collector. Some * time after the collector detects that the reachability of the * referent has changed to the appropriate state, it changes the * instance's state to either Pending or Inactive, depending upon * whether or not the instance was registered with a queue when it was * created. In the former case it also adds the instance to the * pending-Reference list. Newly-created instances are Active. * * Pending: An element of the pending-Reference list, waiting to be * enqueued by the Reference-handler thread. Unregistered instances * are never in this state. * * Enqueued: An element of the queue with which the instance was * registered when it was created. When an instance is removed from * its ReferenceQueue, it is made Inactive. Unregistered instances are * never in this state. * * Inactive: Nothing more to do. Once an instance becomes Inactive its * state will never change again. * * The state is encoded in the queue and next fields as follows: * * Active: queue = ReferenceQueue with which instance is registered, or * ReferenceQueue.NULL if it was not registered with a queue; next = * null. * * Pending: queue = ReferenceQueue with which instance is registered; * next = this * * Enqueued: queue = ReferenceQueue.ENQUEUED; next = Following instance * in queue, or this if at end of list. * * Inactive: queue = ReferenceQueue.NULL; next = this. * * With this scheme the collector need only examine the next field in order * to determine whether a Reference instance requires special treatment: If * the next field is null then the instance is active; if it is non-null, * then the collector should treat the instance normally. * * To ensure that a concurrent collector can discover active Reference * objects without interfering with application threads that may apply * the enqueue() method to those objects, collectors should link * discovered objects through the discovered field. The discovered * field is also used for linking Reference objects in the pending list. */ private T referent; /* Treated specially by GC */ volatile ReferenceQueue queue; /* When active: NULL * pending: this * Enqueued: next reference in queue (or this if last) * Inactive: this */ Reference next; /* When active: next element in a discovered reference list maintained by GC (or this if last) * pending: next element in the pending list (or null if last) * otherwise: NULL */ transient private Reference discovered; /* used by VM */ /* Object used to synchronize with the garbage collector. The collector * must acquire this lock at the beginning of each collection cycle. It is * therefore critical that any code holding this lock complete as quickly * as possible, allocate no new objects, and avoid calling user code. */ static private class Lock { } private static final Lock lock = new Lock(); /* List of References waiting to be enqueued. The collector adds * References to this list, while the Reference-handler thread removes * them. This list is protected by the above lock object. The * list uses the discovered field to link its elements. */ private static Reference pending = null; /* Max. number of Reference(s) to unhook from pending chain in one chunk * before releasing the lock, handling them and grabbing the * lock again. */ private static final int UNHOOK_CHUNK_SIZE = 32768; /* Max. number of Finalizer(s) to execute in one ForkJoinTask */ private static final int FINALIZE_CHUNK_SIZE = 256; /* Max. number of Reference(s) to enqueue in one chunk */ private static final int ENQUEUE_CHUNK_SIZE = 256; private static class ReferenceHandler extends ManagedLocalsThread { private static void ensureClassInitialized(Class clazz) { try { Class.forName(clazz.getName(), true, clazz.getClassLoader()); } catch (ClassNotFoundException e) { throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e); } } static { // pre-load and initialize InterruptedException and Cleaner classes // so that we don't get into trouble later in the run loop if there's // memory shortage while loading/initializing them lazily. ensureClassInitialized(InterruptedException.class); ensureClassInitialized(Cleaner.class); } ReferenceHandler(ThreadGroup g, String name) { super(g, name); } public void run() { // wait for VM to boot-up before starting reference handling // ForkJoinPool since it needs access to some system properties // and Finalizer needs access to SharedSecrets. while (true) { try { sun.misc.VM.awaitBooted(); break; } catch (InterruptedException e) { // ignore; } } // start reference handling ForkJoinPool ReferenceHandling.start(); // enter endless loop boolean[] morePending = new boolean[1]; while (true) { Reference chunk = null; try { synchronized (lock) { chunk = Reference.unhookPendingChunk(UNHOOK_CHUNK_SIZE, morePending); if (chunk == null) { // waiting on notification can throw InterruptedException // if the thread is interrupted, but also OutOfMemoryError // if the InterruptedException can not be allocated. lock.wait(); // since we have already re-obtained the lock, we can // re-try poll and will typically get a non-null chunk. chunk = Reference.unhookPendingChunk(UNHOOK_CHUNK_SIZE, morePending); } } } catch (OutOfMemoryError e) { // give other threads some time so they hopefully release some // references and GC reclaims some space, then retry... Thread.yield(); } catch (InterruptedException e) { // ignore } if (chunk != null) { if (morePending[0]) { // submit a handling task and return for next chunk new ReferenceHandling.PendingChunkHandler(chunk).submit(); } else { // no more pending, so we can handle the chunk directly Reference.handlePendingChunk(chunk); } } } } } /** * Try handle a chunk of pending {@link Reference}s if there are any.

* Return {@code true} as a hint that there are more * {@link Reference}s pending or {@code false} when there are no more pending * {@link Reference}s at the moment and the program can do some other * useful work instead of looping. * * @return {@code true} if there is be more {@link Reference}s pending. */ static boolean tryHandlePending() { Reference r; synchronized (lock) { r = unhookPendingChunk(UNHOOK_CHUNK_SIZE, null); } if (r == null) return false; handlePendingChunk(r); synchronized (lock) { return pending != null; } } /** * Unhooks a chunk of max. {@code chunkSize} references from pending chain and * returns the head of the chunk; elements of the chunk can be reached using * {@link #next} links; the last in chunk is linked to itself. * * @param chunkSize max. number of references to unhook from the pending chain * @param morePending if non null, it should be a boolean array with length 1 * to hold the additional result - a flag indicating that * there are more pending references waiting after a chunk * of them has been returned. * @return the head of the chunk of max. {@code chunkSize} pending references or * null if there are none pending. */ private static Reference unhookPendingChunk(int chunkSize, boolean[] morePending) { // assert Thread.holdsLock(lock); Reference r; if ((r = pending) != null) { // pending state invariant established by VM: // assert r.next == r; // move a chunk of pending/discovered references to a // temporary local r/next chain Reference rd = r.discovered; for (int i = 0; rd != null; rd = r.discovered) { r.discovered = null; if (++i >= chunkSize) { break; } rd.next = r; r = rd; } pending = (Reference) rd; if (morePending != null) morePending[0] = (rd != null); } else { if (morePending != null) morePending[0] = false; } return r; } /** * Handles a non-null chunk of pending references * (obtained using {@link #unhookPendingChunk}) and handles * them as following: *

* @param chunk the head of a chunk of pending references */ static void handlePendingChunk(Reference chunk) { // batch finaliz(ato|e)rs and Finalizators Reference finalizrs = null; int finalizrsCount = 0; // batch consecutive references with same queue into chunks Reference referencesHead = null, referencesTail = null; int referencesCount = 0; ReferenceQueue referenceQueue = null; // dispatch references to appropriate targets for (Reference r = chunk, rn = r.next; ; r = rn, rn = r.next) { if (r instanceof Cleaner) { // Fast path for cleaners // take 'r' off the chain r.next = r; ((Cleaner) r).clean(); } else if (r instanceof Finalizer || r instanceof Finalizator) { // Submit task(s) for finaliz(ato|e)rs // hook onto the finalizers chain r.next = (finalizrs == null) ? r : finalizrs; finalizrs = r; if (++finalizrsCount >= FINALIZE_CHUNK_SIZE) { // when chunk of finaliz(ato|e)rs is full, submit a task new ReferenceHandling.FinalizrHandler(finalizrs).submit(); finalizrs = null; finalizrsCount = 0; } } else { // Enqueue all other references // take 'r' off the chain r.next = r; ReferenceQueue q = r.queue; if (q != ReferenceQueue.NULL && q.markEnqueued(r)) { // markEnqueued is atomic if (referenceQueue == null || referenceQueue == q) { // no queue or same queue -> hook onto the references[Head|Tail] chain if (referencesHead == null) { // assert referencesTail == null && referenceQueue == null && // referencesCount == 0 && r.next == r; referenceQueue = q; referencesHead = referencesTail = r; } else { // assert referencesTail != null && referenceQueue == q && // referencesCount > 0; r.next = referencesHead; referencesHead = r; } if (++referencesCount >= ENQUEUE_CHUNK_SIZE) { // when a chunk of references is full, add them to queue referenceQueue.addChunk(referencesHead, referencesTail); referencesHead = referencesTail = null; referenceQueue = null; referencesCount = 0; } } else { // when a different queue is encountered, // add collected chunk to it's queue and start collecting // into new queue... // assert referenceQueue != null && referenceQueue != q && // referencesHead != null && referencesTail != null && // referencesCount > 0 && r.next == r; referenceQueue.addChunk(referencesHead, referencesTail); referenceQueue = q; referencesHead = referencesTail = r; referencesCount = 1; } } } if (rn == r) { // last in chain break; } } // any finalizers left? if (finalizrs != null) { new ReferenceHandling.FinalizrHandler(finalizrs).submit(); finalizrs = null; finalizrsCount = 0; } // any references left to enqueue? if (referenceQueue != null) { // assert referencesHead != null && referencesTail != null && referencesCount > 0; referenceQueue.addChunk(referencesHead, referencesTail); referencesHead = referencesTail = null; referenceQueue = null; referencesCount = 0; } } /* -- Referent accessor and setters -- */ /** * Returns this reference object's referent. If this reference object has * been cleared, either by the program or by the garbage collector, then * this method returns null. * * @return The object to which this reference refers, or * null if this reference object has been cleared */ public T get() { return this.referent; } /** * Clears this reference object. Invoking this method will not cause this * object to be enqueued. * *

This method is invoked only by Java code; when the garbage collector * clears references it does so directly, without invoking this method. */ public void clear() { this.referent = null; } /* -- Queue operations -- */ /** * Tells whether or not this reference object has been enqueued, either by * the program or by the garbage collector. If this reference object was * not registered with a queue when it was created, then this method will * always return false. * * @return true if and only if this reference object has * been enqueued */ public boolean isEnqueued() { return (this.queue == ReferenceQueue.ENQUEUED); } /** * Adds this reference object to the queue with which it is registered, * if any. * *

This method is invoked only by Java code; when the garbage collector * enqueues references it does so directly, without invoking this method. * * @return true if this reference object was successfully * enqueued; false if it was already enqueued or if * it was not registered with a queue when it was created */ public boolean enqueue() { return this.queue.enqueue(this); } /* -- Constructors -- */ Reference(T referent) { this(referent, null); } Reference(T referent, ReferenceQueue queue) { this.referent = referent; this.queue = (queue == null) ? ReferenceQueue.NULL : queue; } // Unsafe machinery @SuppressWarnings("unchecked") T getReferentVolatile() { return (T) UNSAFE.getObjectVolatile(this, referentOffset); } boolean casReferent(T cmp, T val) { return UNSAFE.compareAndSwapObject(this, referentOffset, cmp, val); } void lazySetQueue(ReferenceQueue val) { UNSAFE.putOrderedObject(this, queueOffset, val); } boolean casQueue(ReferenceQueue cmp, ReferenceQueue val) { return UNSAFE.compareAndSwapObject(this, queueOffset, cmp, val); } private static final sun.misc.Unsafe UNSAFE; private static final long referentOffset; private static final long queueOffset; static { try { UNSAFE = sun.misc.Unsafe.getUnsafe(); Class rc = Reference.class; referentOffset = UNSAFE.objectFieldOffset(rc.getDeclaredField("referent")); queueOffset = UNSAFE.objectFieldOffset(rc.getDeclaredField("queue")); } catch (Exception e) { throw new Error(e); } ThreadGroup tg = Thread.currentThread().getThreadGroup(); for (ThreadGroup tgn = tg; tgn != null; tg = tgn, tgn = tg.getParent()); Thread handler = new ReferenceHandler(tg, "Reference Handler"); /* If there were a special system-only priority greater than * MAX_PRIORITY, it would be used here */ handler.setPriority(Thread.MAX_PRIORITY); handler.setDaemon(true); handler.start(); // provide access in SharedSecrets SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() { @Override public boolean tryHandlePendingReference() { return tryHandlePending(); } }); } }