1 /*
2 * Copyright (c) 1997, 2015, 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
93
94 private T referent; /* Treated specially by GC */
95
96 volatile ReferenceQueue<? super T> queue;
97
98 /* When active: NULL
99 * pending: this
100 * Enqueued: next reference in queue (or this if last)
101 * Inactive: this
102 */
103 @SuppressWarnings("rawtypes")
104 volatile Reference next;
105
106 /* When active: next element in a discovered reference list maintained by GC (or this if last)
107 * pending: next element in the pending list (or null if last)
108 * otherwise: NULL
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 /**
|
1 /*
2 * Copyright (c) 1997, 2016, 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
93
94 private T referent; /* Treated specially by GC */
95
96 volatile ReferenceQueue<? super T> queue;
97
98 /* When active: NULL
99 * pending: this
100 * Enqueued: next reference in queue (or this if last)
101 * Inactive: this
102 */
103 @SuppressWarnings("rawtypes")
104 volatile Reference next;
105
106 /* When active: next element in a discovered reference list maintained by GC (or this if last)
107 * pending: next element in the pending list (or null if last)
108 * otherwise: NULL
109 */
110 private transient Reference<T> discovered; /* used by VM */
111
112
113 /* High-priority thread to enqueue pending References
114 */
115 private static class ReferenceHandler extends Thread {
116
117 private static void ensureClassInitialized(Class<?> clazz) {
118 try {
119 Class.forName(clazz.getName(), true, clazz.getClassLoader());
120 } catch (ClassNotFoundException e) {
121 throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e);
122 }
123 }
124
125 static {
126 // pre-load and initialize Cleaner class so that we don't
127 // get into trouble later in the run loop if there's
128 // memory shortage while loading/initializing it lazily.
129 ensureClassInitialized(Cleaner.class);
130 }
131
132 ReferenceHandler(ThreadGroup g, String name) {
133 super(g, null, name, 0, false);
134 }
135
136 public void run() {
137 while (true) {
138 processPendingReferences();
139 }
140 }
141 }
142
143 /* Atomically get and clear (set to null) the VM's pending list.
144 */
145 private static native Reference<Object> getAndClearReferencePendingList();
146
147 /* Atomically test whether the VM's pending list contains any
148 * entries. If not, and await is true, then block until the
149 * pending list becomes non-empty. The GC adds references to the
150 * pending list and notifies waiting threads when references are
151 * added. Returns true when the pending list was found to be
152 * non-empty.
153 */
154 private static native boolean checkReferencePendingList(boolean await);
155
156 private static final Object processPendingLock = new Object();
157 private static boolean processPendingActive = false;
158
159 private static void processPendingReferences() {
160 checkReferencePendingList(true);
161 Reference<Object> pendingList;
162 synchronized (processPendingLock) {
163 pendingList = getAndClearReferencePendingList();
164 processPendingActive = true;
165 }
166 while (pendingList != null) {
167 Reference<Object> ref = pendingList;
168 pendingList = ref.discovered;
169 ref.discovered = null;
170
171 if (ref instanceof Cleaner) {
172 ((Cleaner)ref).clean();
173 // Notify any waiters that progress has been made.
174 // This improves latency for nio.Bits waiters, which
175 // are the only important ones.
176 synchronized (processPendingLock) {
177 processPendingLock.notifyAll();
178 }
179 } else {
180 ReferenceQueue<? super Object> q = ref.queue;
181 if (q != ReferenceQueue.NULL) q.enqueue(ref);
182 }
183 }
184 // Notify any waiters of completion of current round.
185 synchronized (processPendingLock) {
186 processPendingActive = false;
187 processPendingLock.notifyAll();
188 }
189 }
190
191 /**
192 * Wait for progress in {@link Reference} processing. If there
193 * aren't any pending {@link Reference}s, return immediately.
194 *
195 * @return {@code true} if there were any pending {@link Reference}s,
196 * {@code false} otherwise.
197 */
198 private static boolean waitForReferenceProcessing()
199 throws InterruptedException
200 {
201 synchronized (processPendingLock) {
202 if (processPendingActive || checkReferencePendingList(false)) {
203 // Wait for progress, not necessarily completion.
204 processPendingLock.wait();
205 return true;
206 } else {
207 return false;
208 }
209 }
210 }
211
212 static {
213 ThreadGroup tg = Thread.currentThread().getThreadGroup();
214 for (ThreadGroup tgn = tg;
215 tgn != null;
216 tg = tgn, tgn = tg.getParent());
217 Thread handler = new ReferenceHandler(tg, "Reference Handler");
218 /* If there were a special system-only priority greater than
219 * MAX_PRIORITY, it would be used here
220 */
221 handler.setPriority(Thread.MAX_PRIORITY);
222 handler.setDaemon(true);
223 handler.start();
224
225 // provide access in SharedSecrets
226 SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {
227 @Override
228 public boolean waitForReferenceProcessing()
229 throws InterruptedException
230 {
231 return Reference.waitForReferenceProcessing();
232 }
233 });
234 }
235
236 /* -- Referent accessor and setters -- */
237
238 /**
239 * Returns this reference object's referent. If this reference object has
240 * been cleared, either by the program or by the garbage collector, then
241 * this method returns <code>null</code>.
242 *
243 * @return The object to which this reference refers, or
244 * <code>null</code> if this reference object has been cleared
245 */
246 @HotSpotIntrinsicCandidate
247 public T get() {
248 return this.referent;
249 }
250
251 /**
|