1 /* 2 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package java.lang.ref; 27 28 import sun.misc.Cleaner; 29 import sun.misc.Unsafe; 30 31 /** 32 * Abstract base class for reference objects. This class defines the 33 * operations common to all reference objects. Because reference objects are 34 * implemented in close cooperation with the garbage collector, this class may 35 * not be subclassed directly. 36 * 37 * @author Mark Reinhold 38 * @since 1.2 39 */ 40 41 public abstract class Reference<T> { 42 43 /* A Reference instance is in one of four possible internal states: 44 * 45 * Active: Subject to special treatment by the garbage collector. Some 46 * time after the collector detects that the reachability of the 47 * referent has changed to the appropriate state, it changes the 48 * instance's state to either Pending or Inactive, depending upon 49 * whether or not the instance was registered with a queue when it was 50 * created. In the former case it also adds the instance to the 51 * pending-Reference list. Newly-created instances are Active. 52 * 53 * Pending: An element of the pending-Reference list, waiting to be 54 * enqueued by the Reference-handler thread. Unregistered instances 55 * are never in this state. 56 * 57 * Enqueued: An element of the queue with which the instance was 58 * registered when it was created. When an instance is removed from 59 * its ReferenceQueue, it is made Inactive. Unregistered instances are 60 * never in this state. 61 * 62 * Inactive: Nothing more to do. Once an instance becomes Inactive its 63 * state will never change again. 64 * 65 * The state is encoded in the queue and next fields as follows: 66 * 67 * Active: queue = ReferenceQueue with which instance is registered, or 68 * ReferenceQueue.NULL if it was not registered with a queue; next = 69 * null. 70 * 71 * Pending: queue = ReferenceQueue with which instance is registered; 72 * next = this 73 * 74 * Enqueued: queue = ReferenceQueue.ENQUEUED; next = Following instance 75 * in queue, or this if at end of list. 76 * 77 * Inactive: queue = ReferenceQueue.NULL; next = this. 78 * 79 * With this scheme the collector need only examine the next field in order 80 * to determine whether a Reference instance requires special treatment: If 81 * the next field is null then the instance is active; if it is non-null, 82 * then the collector should treat the instance normally. 83 * 84 * To ensure that a concurrent collector can discover active Reference 85 * objects without interfering with application threads that may apply 86 * the enqueue() method to those objects, collectors should link 87 * discovered objects through the discovered field. The discovered 88 * field is also used for linking Reference objects in the pending list. 89 */ 90 91 private T referent; /* Treated specially by GC */ 92 93 volatile ReferenceQueue<? super T> queue; 94 95 /* When active: NULL 96 * pending: this 97 * Enqueued: next reference in queue (or this if last) 98 * Inactive: this 99 */ 100 @SuppressWarnings("rawtypes") 101 Reference next; 102 103 /* When active: next element in a discovered reference list maintained by GC (or this if last) 104 * pending: next element in the pending list (or null if last) 105 * otherwise: NULL 106 */ 107 transient private Reference<T> discovered; /* used by VM */ 108 109 110 /* Object used to synchronize with the garbage collector. The collector 111 * must acquire this lock at the beginning of each collection cycle. It is 112 * therefore critical that any code holding this lock complete as quickly 113 * as possible, allocate no new objects, and avoid calling user code. 114 */ 115 static private class Lock { }; 116 private static Lock lock = new Lock(); 117 118 119 /* List of References waiting to be enqueued. The collector adds 120 * References to this list, while the Reference-handler thread removes 121 * them. This list is protected by the above lock object. The 122 * list uses the discovered field to link its elements. 123 */ 124 private static Reference<Object> pending = null; 125 126 /* High-priority thread to enqueue pending References 127 */ 128 private static class ReferenceHandler extends Thread { 129 130 static { 131 // pre-load and initialize InterruptedException and Cleaner classes 132 // so that we don't get into trouble later in the run loop if there's 133 // memory shortage while loading/initializing them lazily. 134 Unsafe unsafe = Unsafe.getUnsafe(); 135 unsafe.ensureClassInitialized(InterruptedException.class); 136 unsafe.ensureClassInitialized(Cleaner.class); 137 } 138 139 ReferenceHandler(ThreadGroup g, String name) { 140 super(g, name); 141 } 142 143 public void run() { 144 for (;;) { 145 Reference<Object> r; 146 Cleaner c; 147 try { 148 synchronized (lock) { 149 if (pending != null) { 150 r = pending; 151 // 'instanceof' might throw OOME sometimes so do this before 152 // unlinking 'r' from the 'pending' chain... 153 c = r instanceof Cleaner ? (Cleaner) r : null; 154 // unlink 'r' from 'pending' chain 155 pending = r.discovered; 156 r.discovered = null; 157 } else { 158 // The waiting on the lock may cause an OOME because it may try to allocate 159 // exception objects. 160 lock.wait(); 161 continue; 162 } 163 } 164 } catch (OutOfMemoryError x) { 165 // Catch OOME from 'r instanceof Cleaner' or 'lock.wait()'. 166 // Give other threads CPU time so they hopefully drop some live references 167 // and GC reclaims some space. 168 // Also prevent CPU intensive spinning in case 'r instanceof Cleaner' above 169 // persistently throws OOME for some time... 170 Thread.yield(); 171 // retry 172 continue; 173 } catch (InterruptedException x) { 174 // Catch InterruptedException from 'lock.wait()' and retry 175 continue; 176 } 177 178 // Fast path for cleaners 179 if (c != null) { 180 c.clean(); 181 continue; 182 } 183 184 ReferenceQueue<Object> q = r.queue; 185 if (q != ReferenceQueue.NULL) q.enqueue(r); 186 } 187 } 188 } 189 190 static { 191 ThreadGroup tg = Thread.currentThread().getThreadGroup(); 192 for (ThreadGroup tgn = tg; 193 tgn != null; 194 tg = tgn, tgn = tg.getParent()); 195 Thread handler = new ReferenceHandler(tg, "Reference Handler"); 196 /* If there were a special system-only priority greater than 197 * MAX_PRIORITY, it would be used here 198 */ 199 handler.setPriority(Thread.MAX_PRIORITY); 200 handler.setDaemon(true); 201 handler.start(); 202 } 203 204 205 /* -- Referent accessor and setters -- */ 206 207 /** 208 * Returns this reference object's referent. If this reference object has 209 * been cleared, either by the program or by the garbage collector, then 210 * this method returns <code>null</code>. 211 * 212 * @return The object to which this reference refers, or 213 * <code>null</code> if this reference object has been cleared 214 */ 215 public T get() { 216 return this.referent; 217 } 218 219 /** 220 * Clears this reference object. Invoking this method will not cause this 221 * object to be enqueued. 222 * 223 * <p> This method is invoked only by Java code; when the garbage collector 224 * clears references it does so directly, without invoking this method. 225 */ 226 public void clear() { 227 this.referent = null; 228 } 229 230 231 /* -- Queue operations -- */ 232 233 /** 234 * Tells whether or not this reference object has been enqueued, either by 235 * the program or by the garbage collector. If this reference object was 236 * not registered with a queue when it was created, then this method will 237 * always return <code>false</code>. 238 * 239 * @return <code>true</code> if and only if this reference object has 240 * been enqueued 241 */ 242 public boolean isEnqueued() { 243 return (this.queue == ReferenceQueue.ENQUEUED); 244 } 245 246 /** 247 * Adds this reference object to the queue with which it is registered, 248 * if any. 249 * 250 * <p> This method is invoked only by Java code; when the garbage collector 251 * enqueues references it does so directly, without invoking this method. 252 * 253 * @return <code>true</code> if this reference object was successfully 254 * enqueued; <code>false</code> if it was already enqueued or if 255 * it was not registered with a queue when it was created 256 */ 257 public boolean enqueue() { 258 return this.queue.enqueue(this); 259 } 260 261 262 /* -- Constructors -- */ 263 264 Reference(T referent) { 265 this(referent, null); 266 } 267 268 Reference(T referent, ReferenceQueue<? super T> queue) { 269 this.referent = referent; 270 this.queue = (queue == null) ? ReferenceQueue.NULL : queue; 271 } 272 273 }