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 jdk.internal.vm.annotation.DontInline;
29 import jdk.internal.HotSpotIntrinsicCandidate;
30 import jdk.internal.misc.JavaLangRefAccess;
31 import jdk.internal.misc.SharedSecrets;
32 import jdk.internal.ref.Cleaner;
33
34 /**
35 * Abstract base class for reference objects. This class defines the
36 * operations common to all reference objects. Because reference objects are
37 * implemented in close cooperation with the garbage collector, this class may
38 * not be subclassed directly.
39 *
40 * @author Mark Reinhold
41 * @since 1.2
42 */
43
44 public abstract class Reference<T> {
45
46 /* A Reference instance is in one of four possible internal states:
47 *
48 * Active: Subject to special treatment by the garbage collector. Some
49 * time after the collector detects that the reachability of the
50 * referent has changed to the appropriate state, it changes the
51 * instance's state to either Pending or Inactive, depending upon
52 * whether or not the instance was registered with a queue when it was
109 */
110 private transient Reference<T> discovered; /* used by VM */
111
112
113 /* Object used to synchronize with the garbage collector. The collector
114 * must acquire this lock at the beginning of each collection cycle. It is
115 * therefore critical that any code holding this lock complete as quickly
116 * as possible, allocate no new objects, and avoid calling user code.
117 */
118 private static class Lock { }
119 private static Lock lock = new Lock();
120
121
122 /* List of References waiting to be enqueued. The collector adds
123 * References to this list, while the Reference-handler thread removes
124 * them. This list is protected by the above lock object. The
125 * list uses the discovered field to link its elements.
126 */
127 private static Reference<Object> pending = null;
128
129 /* High-priority thread to enqueue pending References
130 */
131 private static class ReferenceHandler extends Thread {
132
133 private static void ensureClassInitialized(Class<?> clazz) {
134 try {
135 Class.forName(clazz.getName(), true, clazz.getClassLoader());
136 } catch (ClassNotFoundException e) {
137 throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e);
138 }
139 }
140
141 static {
142 // pre-load and initialize InterruptedException and Cleaner classes
143 // so that we don't get into trouble later in the run loop if there's
144 // memory shortage while loading/initializing them lazily.
145 ensureClassInitialized(InterruptedException.class);
146 ensureClassInitialized(Cleaner.class);
147 }
148
149 ReferenceHandler(ThreadGroup g, String name) {
150 super(g, null, name, 0, false);
151 }
152
153 public void run() {
154 while (true) {
155 tryHandlePending(true);
156 }
157 }
158 }
159
160 /**
161 * Try handle pending {@link Reference} if there is one.<p>
162 * Return {@code true} as a hint that there might be another
163 * {@link Reference} pending or {@code false} when there are no more pending
164 * {@link Reference}s at the moment and the program can do some other
165 * useful work instead of looping.
166 *
167 * @param waitForNotify if {@code true} and there was no pending
168 * {@link Reference}, wait until notified from VM
169 * or interrupted; if {@code false}, return immediately
170 * when there is no pending {@link Reference}.
171 * @return {@code true} if there was a {@link Reference} pending and it
172 * was processed, or we waited for notification and either got it
173 * or thread was interrupted before being notified;
174 * {@code false} otherwise.
175 */
176 static boolean tryHandlePending(boolean waitForNotify) {
177 Reference<Object> r;
178 Cleaner c;
179 try {
180 synchronized (lock) {
181 if (pending != null) {
182 r = pending;
183 // 'instanceof' might throw OutOfMemoryError sometimes
184 // so do this before un-linking 'r' from the 'pending' chain...
185 c = r instanceof Cleaner ? (Cleaner) r : null;
186 // unlink 'r' from 'pending' chain
187 pending = r.discovered;
188 r.discovered = null;
189 } else {
190 // The waiting on the lock may cause an OutOfMemoryError
191 // because it may try to allocate exception objects.
192 if (waitForNotify) {
193 lock.wait();
194 }
195 // retry if waited
196 return waitForNotify;
197 }
198 }
199 } catch (OutOfMemoryError x) {
200 // Give other threads CPU time so they hopefully drop some live references
201 // and GC reclaims some space.
202 // Also prevent CPU intensive spinning in case 'r instanceof Cleaner' above
203 // persistently throws OOME for some time...
204 Thread.yield();
205 // retry
206 return true;
207 } catch (InterruptedException x) {
208 // retry
209 return true;
210 }
211
212 // Fast path for cleaners
213 if (c != null) {
214 c.clean();
215 return true;
216 }
217
218 ReferenceQueue<? super Object> q = r.queue;
219 if (q != ReferenceQueue.NULL) q.enqueue(r);
220 return true;
221 }
222
223 static {
224 ThreadGroup tg = Thread.currentThread().getThreadGroup();
225 for (ThreadGroup tgn = tg;
226 tgn != null;
227 tg = tgn, tgn = tg.getParent());
228 Thread handler = new ReferenceHandler(tg, "Reference Handler");
229 /* If there were a special system-only priority greater than
230 * MAX_PRIORITY, it would be used here
231 */
232 handler.setPriority(Thread.MAX_PRIORITY);
233 handler.setDaemon(true);
234 handler.start();
235
236 // provide access in SharedSecrets
237 SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {
238 @Override
239 public boolean tryHandlePendingReference() {
240 return tryHandlePending(false);
241 }
242 });
243 }
244
245 /* -- Referent accessor and setters -- */
246
247 /**
248 * Returns this reference object's referent. If this reference object has
249 * been cleared, either by the program or by the garbage collector, then
250 * this method returns <code>null</code>.
251 *
252 * @return The object to which this reference refers, or
253 * <code>null</code> if this reference object has been cleared
254 */
255 @HotSpotIntrinsicCandidate
256 public T get() {
257 return this.referent;
258 }
259
260 /**
|
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 jdk.internal.vm.annotation.DontInline;
29 import jdk.internal.HotSpotIntrinsicCandidate;
30 import jdk.internal.misc.JavaLangRefAccess;
31 import jdk.internal.misc.SharedSecrets;
32
33 /**
34 * Abstract base class for reference objects. This class defines the
35 * operations common to all reference objects. Because reference objects are
36 * implemented in close cooperation with the garbage collector, this class may
37 * not be subclassed directly.
38 *
39 * @author Mark Reinhold
40 * @since 1.2
41 */
42
43 public abstract class Reference<T> {
44
45 /* A Reference instance is in one of four possible internal states:
46 *
47 * Active: Subject to special treatment by the garbage collector. Some
48 * time after the collector detects that the reachability of the
49 * referent has changed to the appropriate state, it changes the
50 * instance's state to either Pending or Inactive, depending upon
51 * whether or not the instance was registered with a queue when it was
108 */
109 private transient Reference<T> discovered; /* used by VM */
110
111
112 /* Object used to synchronize with the garbage collector. The collector
113 * must acquire this lock at the beginning of each collection cycle. It is
114 * therefore critical that any code holding this lock complete as quickly
115 * as possible, allocate no new objects, and avoid calling user code.
116 */
117 private static class Lock { }
118 private static Lock lock = new Lock();
119
120
121 /* List of References waiting to be enqueued. The collector adds
122 * References to this list, while the Reference-handler thread removes
123 * them. This list is protected by the above lock object. The
124 * list uses the discovered field to link its elements.
125 */
126 private static Reference<Object> pending = null;
127
128 /* Phase counters. Guarded by the above lock object.
129 */
130 private static int unhookPhase;
131 private static int enqueuePhase;
132
133 /* High-priority thread to enqueue pending References
134 */
135 private static class ReferenceHandler extends Thread {
136
137 private static void ensureClassInitialized(Class<?> clazz) {
138 try {
139 Class.forName(clazz.getName(), true, clazz.getClassLoader());
140 } catch (ClassNotFoundException e) {
141 throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e);
142 }
143 }
144
145 static {
146 // pre-load and initialize InterruptedException class
147 // so that we don't get into trouble later in the run loop if there's
148 // memory shortage while loading/initializing it lazily.
149 ensureClassInitialized(InterruptedException.class);
150 }
151
152 ReferenceHandler(ThreadGroup g, String name) {
153 super(g, null, name, 0, false);
154 }
155
156 public void run() {
157 while (true) {
158 enqueuePendingReferences(true);
159 }
160 }
161 }
162
163 /**
164 * Enqueue pending {@link Reference}s if GC has discovered any.<p>
165 * This method does not return until all references that had been discovered
166 * by the time this method was called, are enqueued even if some of them are
167 * being enqueued concurrently by other threads.
168 *
169 * @param waitForNotifyFromGc if {@code true} and there is no pending
170 * {@link Reference}, wait until VM discovers some
171 * or interrupted (in which case the interrupted
172 * status is cleared); if {@code false} and there
173 * is no pending reference, just wait until threads
174 * that found some discovered references before
175 * us enqueue them all.
176 */
177 static void enqueuePendingReferences(boolean waitForNotifyFromGc) {
178 Reference<Object> p;
179 int unhookedInPhase;
180 try {
181 synchronized (lock) {
182 while ((p = pending) == null && waitForNotifyFromGc) {
183 lock.wait();
184 }
185 // unhook the whole chain of pending References at once
186 pending = null;
187 // remember the phase in which we unhooked a chain
188 // of pending references and increment the counter
189 unhookedInPhase = unhookPhase++;
190 }
191 } catch (OutOfMemoryError x) {
192 // The waiting on the lock may cause an OutOfMemoryError
193 // because it may try to allocate InterruptedException object.
194 // Give other threads CPU time so they hopefully drop some live
195 // references and GC reclaims some space.
196 Thread.yield();
197 return;
198 } catch (InterruptedException x) {
199 return;
200 }
201
202 try {
203 // distribute unhooked pending references to their respective queues
204 while (p != null) {
205 Reference<Object> r = p;
206 p = r.discovered;
207 r.discovered = null;
208 ReferenceQueue<? super Object> q = r.queue;
209 if (q != ReferenceQueue.NULL) q.enqueue(r);
210 }
211 } finally {
212 boolean interrupted = false;
213 synchronized (lock) {
214 // wait for concurrent enqueuing threads that unhooked
215 // pending references before us to finish with enqueueing
216 // before proceeding...
217 try {
218 while (unhookedInPhase - enqueuePhase > 0) {
219 try {
220 lock.wait();
221 } catch (OutOfMemoryError e) {
222 // The waiting on the lock may cause an OutOfMemoryError
223 // (we swallow such interrupt as we are not sure about
224 // OOME cause).
225 Thread.yield();
226 } catch (InterruptedException e) {
227 // remember that we were interrupted
228 interrupted = true;
229 }
230 }
231 } finally {
232 // increment enqueue phase counter
233 enqueuePhase++;
234 // notify waiters
235 lock.notifyAll();
236 }
237 }
238 // re-assert thread interrupted status
239 if (interrupted) {
240 Thread.currentThread().interrupt();
241 }
242 }
243 }
244
245 static {
246 ThreadGroup tg = Thread.currentThread().getThreadGroup();
247 for (ThreadGroup tgn = tg;
248 tgn != null;
249 tg = tgn, tgn = tg.getParent());
250 Thread handler = new ReferenceHandler(tg, "Reference Handler");
251 /* If there were a special system-only priority greater than
252 * MAX_PRIORITY, it would be used here
253 */
254 handler.setPriority(Thread.MAX_PRIORITY);
255 handler.setDaemon(true);
256 handler.start();
257
258 // provide access in SharedSecrets
259 SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {
260 @Override
261 public void enqueuePendingReferences() {
262 Reference.enqueuePendingReferences(false);
263 }
264
265 @Override
266 public boolean cleanNextEnqueuedCleanable(Cleaner cleaner) {
267 return cleaner.cleanNextEnqueued();
268 }
269 });
270 }
271
272 /* -- Referent accessor and setters -- */
273
274 /**
275 * Returns this reference object's referent. If this reference object has
276 * been cleared, either by the program or by the garbage collector, then
277 * this method returns <code>null</code>.
278 *
279 * @return The object to which this reference refers, or
280 * <code>null</code> if this reference object has been cleared
281 */
282 @HotSpotIntrinsicCandidate
283 public T get() {
284 return this.referent;
285 }
286
287 /**
|