1 /*
  2  * Copyright (c) 1997, 2021, 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 jdk.internal.vm.annotation.ForceInline;
 29 import jdk.internal.vm.annotation.IntrinsicCandidate;
 30 import jdk.internal.access.JavaLangRefAccess;
 31 import jdk.internal.access.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     /* The state of a Reference object is characterized by two attributes.  It
 47      * may be either "active", "pending", or "inactive".  It may also be
 48      * either "registered", "enqueued", "dequeued", or "unregistered".
 49      *
 50      *   Active: Subject to special treatment by the garbage collector.  Some
 51      *   time after the collector detects that the reachability of the
 52      *   referent has changed to the appropriate state, the collector
 53      *   "notifies" the reference, changing the state to either "pending" or
 54      *   "inactive".
 55      *   referent != null; discovered = null, or in GC discovered list.
 56      *
 57      *   Pending: An element of the pending-Reference list, waiting to be
 58      *   processed by the ReferenceHandler thread.  The pending-Reference
 59      *   list is linked through the discovered fields of references in the
 60      *   list.
 61      *   referent = null; discovered = next element in pending-Reference list.
 62      *
 63      *   Inactive: Neither Active nor Pending.
 64      *   referent = null.
 65      *
 66      *   Registered: Associated with a queue when created, and not yet added
 67      *   to the queue.
 68      *   queue = the associated queue.
 69      *
 70      *   Enqueued: Added to the associated queue, and not yet removed.
 71      *   queue = ReferenceQueue.ENQUEUE; next = next entry in list, or this to
 72      *   indicate end of list.
 73      *
 74      *   Dequeued: Added to the associated queue and then removed.
 75      *   queue = ReferenceQueue.NULL; next = this.
 76      *
 77      *   Unregistered: Not associated with a queue when created.
 78      *   queue = ReferenceQueue.NULL.
 79      *
 80      * The collector only needs to examine the referent field and the
 81      * discovered field to determine whether a (non-FinalReference) Reference
 82      * object needs special treatment.  If the referent is non-null and not
 83      * known to be live, then it may need to be discovered for possible later
 84      * notification.  But if the discovered field is non-null, then it has
 85      * already been discovered.
 86      *
 87      * FinalReference (which exists to support finalization) differs from
 88      * other references, because a FinalReference is not cleared when
 89      * notified.  The referent being null or not cannot be used to distinguish
 90      * between the active state and pending or inactive states.  However,
 91      * FinalReferences do not support enqueue().  Instead, the next field of a
 92      * FinalReference object is set to "this" when it is added to the
 93      * pending-Reference list.  The use of "this" as the value of next in the
 94      * enqueued and dequeued states maintains the non-active state.  An
 95      * additional check that the next field is null is required to determine
 96      * that a FinalReference object is active.
 97      *
 98      * Initial states:
 99      *   [active/registered]
100      *   [active/unregistered] [1]
101      *
102      * Transitions:
103      *                            clear [2]
104      *   [active/registered]     ------->   [inactive/registered]
105      *          |                                 |
106      *          |                                 | enqueue
107      *          | GC              enqueue [2]     |
108      *          |                -----------------|
109      *          |                                 |
110      *          v                                 |
111      *   [pending/registered]    ---              v
112      *          |                   | ReferenceHandler
113      *          | enqueue [2]       |--->   [inactive/enqueued]
114      *          v                   |             |
115      *   [pending/enqueued]      ---              |
116      *          |                                 | poll/remove
117      *          | poll/remove                     | + clear [4]
118      *          |                                 |
119      *          v            ReferenceHandler     v
120      *   [pending/dequeued]      ------>    [inactive/dequeued]
121      *
122      *
123      *                           clear/enqueue/GC [3]
124      *   [active/unregistered]   ------
125      *          |                      |
126      *          | GC                   |
127      *          |                      |--> [inactive/unregistered]
128      *          v                      |
129      *   [pending/unregistered]  ------
130      *                           ReferenceHandler
131      *
132      * Terminal states:
133      *   [inactive/dequeued]
134      *   [inactive/unregistered]
135      *
136      * Unreachable states (because enqueue also clears):
137      *   [active/enqueued]
138      *   [active/dequeued]
139      *
140      * [1] Unregistered is not permitted for FinalReferences.
141      *
142      * [2] These transitions are not possible for FinalReferences, making
143      * [pending/enqueued], [pending/dequeued], and [inactive/registered]
144      * unreachable.
145      *
146      * [3] The garbage collector may directly transition a Reference
147      * from [active/unregistered] to [inactive/unregistered],
148      * bypassing the pending-Reference list.
149      *
150      * [4] The queue handler for FinalReferences also clears the reference.
151      */
152 
153     private T referent;         /* Treated specially by GC */
154 
155     /* The queue this reference gets enqueued to by GC notification or by
156      * calling enqueue().
157      *
158      * When registered: the queue with which this reference is registered.
159      *        enqueued: ReferenceQueue.ENQUEUE
160      *        dequeued: ReferenceQueue.NULL
161      *    unregistered: ReferenceQueue.NULL
162      */
163     volatile ReferenceQueue<? super T> queue;
164 
165     /* The link in a ReferenceQueue's list of Reference objects.
166      *
167      * When registered: null
168      *        enqueued: next element in queue (or this if last)
169      *        dequeued: this (marking FinalReferences as inactive)
170      *    unregistered: null
171      */
172     @SuppressWarnings("rawtypes")
173     volatile Reference next;
174 
175     /* Used by the garbage collector to accumulate Reference objects that need
176      * to be revisited in order to decide whether they should be notified.
177      * Also used as the link in the pending-Reference list.  The discovered
178      * field and the next field are distinct to allow the enqueue() method to
179      * be applied to a Reference object while it is either in the
180      * pending-Reference list or in the garbage collector's discovered set.
181      *
182      * When active: null or next element in a discovered reference list
183      *              maintained by the GC (or this if last)
184      *     pending: next element in the pending-Reference list (null if last)
185      *    inactive: null
186      */
187     private transient Reference<?> discovered;
188 
189 
190     /* High-priority thread to enqueue pending References
191      */
192     private static class ReferenceHandler extends Thread {
193 
194         private static void ensureClassInitialized(Class<?> clazz) {
195             try {
196                 Class.forName(clazz.getName(), true, clazz.getClassLoader());
197             } catch (ClassNotFoundException e) {
198                 throw (Error) new NoClassDefFoundError(e.getMessage()).initCause(e);
199             }
200         }
201 
202         static {
203             // pre-load and initialize Cleaner class so that we don't
204             // get into trouble later in the run loop if there's
205             // memory shortage while loading/initializing it lazily.
206             ensureClassInitialized(Cleaner.class);
207         }
208 
209         ReferenceHandler(ThreadGroup g, String name) {
210             super(g, null, name, 0, false);
211         }
212 
213         public void run() {
214             while (true) {
215                 processPendingReferences();
216             }
217         }
218     }
219 
220     /*
221      * Atomically get and clear (set to null) the VM's pending-Reference list.
222      */
223     private static native Reference<?> getAndClearReferencePendingList();
224 
225     /*
226      * Test whether the VM's pending-Reference list contains any entries.
227      */
228     private static native boolean hasReferencePendingList();
229 
230     /*
231      * Wait until the VM's pending-Reference list may be non-null.
232      */
233     private static native void waitForReferencePendingList();
234 
235     /*
236      * Enqueue a Reference taken from the pending list.  Calling this method
237      * takes us from the Reference<?> domain of the pending list elements to
238      * having a Reference<T> with a correspondingly typed queue.
239      */
240     private void enqueueFromPending() {
241         var q = queue;
242         if (q != ReferenceQueue.NULL) q.enqueue(this);
243     }
244 
245     private static final Object processPendingLock = new Object();
246     private static boolean processPendingActive = false;
247 
248     private static void processPendingReferences() {
249         // Only the singleton reference processing thread calls
250         // waitForReferencePendingList() and getAndClearReferencePendingList().
251         // These are separate operations to avoid a race with other threads
252         // that are calling waitForReferenceProcessing().
253         waitForReferencePendingList();
254         Reference<?> pendingList;
255         synchronized (processPendingLock) {
256             pendingList = getAndClearReferencePendingList();
257             processPendingActive = true;
258         }
259         while (pendingList != null) {
260             Reference<?> ref = pendingList;
261             pendingList = ref.discovered;
262             ref.discovered = null;
263 
264             if (ref instanceof Cleaner) {
265                 ((Cleaner)ref).clean();
266                 // Notify any waiters that progress has been made.
267                 // This improves latency for nio.Bits waiters, which
268                 // are the only important ones.
269                 synchronized (processPendingLock) {
270                     processPendingLock.notifyAll();
271                 }
272             } else {
273                 ref.enqueueFromPending();
274             }
275         }
276         // Notify any waiters of completion of current round.
277         synchronized (processPendingLock) {
278             processPendingActive = false;
279             processPendingLock.notifyAll();
280         }
281     }
282 
283     // Wait for progress in reference processing.
284     //
285     // Returns true after waiting (for notification from the reference
286     // processing thread) if either (1) the VM has any pending
287     // references, or (2) the reference processing thread is
288     // processing references. Otherwise, returns false immediately.
289     private static boolean waitForReferenceProcessing()
290         throws InterruptedException
291     {
292         synchronized (processPendingLock) {
293             if (processPendingActive || hasReferencePendingList()) {
294                 // Wait for progress, not necessarily completion.
295                 processPendingLock.wait();
296                 return true;
297             } else {
298                 return false;
299             }
300         }
301     }
302 
303     static {
304         ThreadGroup tg = Thread.currentThread().getThreadGroup();
305         for (ThreadGroup tgn = tg;
306              tgn != null;
307              tg = tgn, tgn = tg.getParent());
308         Thread handler = new ReferenceHandler(tg, "Reference Handler");
309         /* If there were a special system-only priority greater than
310          * MAX_PRIORITY, it would be used here
311          */
312         handler.setPriority(Thread.MAX_PRIORITY);
313         handler.setDaemon(true);
314         handler.start();
315 
316         // provide access in SharedSecrets
317         SharedSecrets.setJavaLangRefAccess(new JavaLangRefAccess() {
318             @Override
319             public boolean waitForReferenceProcessing()
320                 throws InterruptedException
321             {
322                 return Reference.waitForReferenceProcessing();
323             }
324 
325             @Override
326             public void runFinalization() {
327                 Finalizer.runFinalization();
328             }
329         });
330     }
331 
332     /* -- Referent accessor and setters -- */
333 
334     /**
335      * Returns this reference object's referent.  If this reference object has
336      * been cleared, either by the program or by the garbage collector, then
337      * this method returns {@code null}.
338      *
339      * @apiNote
340      * This method returns a strong reference to the referent. This may cause
341      * the garbage collector to treat it as strongly reachable until some later
342      * collection cycle.  The {@link #refersTo(Object) refersTo} method can be
343      * used to avoid such strengthening when testing whether some object is
344      * the referent of a reference object; that is, use {@code ref.refersTo(obj)}
345      * rather than {@code ref.get() == obj}.
346      *
347      * @return   The object to which this reference refers, or
348      *           {@code null} if this reference object has been cleared
349      * @see #refersTo
350      */
351     @IntrinsicCandidate
352     public T get() {
353         return this.referent;
354     }
355 
356     /**
357      * Tests if the referent of this reference object is {@code obj}.
358      * Using a {@code null} {@code obj} returns {@code true} if the
359      * reference object has been cleared.
360      *
361      * @param  obj the object to compare with this reference object's referent
362      * @return {@code true} if {@code obj} is the referent of this reference object
363      * @since 16
364      */
365     public final boolean refersTo(T obj) {
366         return refersToImpl(obj);
367     }
368 
369     /* Implementation of refersTo(), overridden for phantom references.
370      * This method exists only to avoid making refersTo0() virtual. Making
371      * refersTo0() virtual has the undesirable effect of C2 often preferring
372      * to call the native implementation over the intrinsic.
373      */
374     boolean refersToImpl(T obj) {
375         return refersTo0(obj);
376     }
377 
378     @IntrinsicCandidate
379     private native boolean refersTo0(Object o);
380 
381     /**
382      * Clears this reference object.  Invoking this method will not cause this
383      * object to be enqueued.
384      *
385      * <p> This method is invoked only by Java code; when the garbage collector
386      * clears references it does so directly, without invoking this method.
387      */
388     public void clear() {
389         clear0();
390     }
391 
392     /* Implementation of clear(), also used by enqueue().  A simple
393      * assignment of the referent field won't do for some garbage
394      * collectors.
395      */
396     private native void clear0();
397 
398     /* -- Operations on inactive FinalReferences -- */
399 
400     /* These functions are only used by FinalReference, and must only be
401      * called after the reference becomes inactive. While active, a
402      * FinalReference is considered weak but the referent is not normally
403      * accessed. Once a FinalReference becomes inactive it is considered a
404      * strong reference. These functions are used to bypass the
405      * corresponding weak implementations, directly accessing the referent
406      * field with strong semantics.
407      */
408 
409     /**
410      * Load referent with strong semantics.
411      */
412     T getFromInactiveFinalReference() {
413         assert this instanceof FinalReference;
414         assert next != null; // I.e. FinalReference is inactive
415         return this.referent;
416     }
417 
418     /**
419      * Clear referent with strong semantics.
420      */
421     void clearInactiveFinalReference() {
422         assert this instanceof FinalReference;
423         assert next != null; // I.e. FinalReference is inactive
424         this.referent = null;
425     }
426 
427     /* -- Queue operations -- */
428 
429     /**
430      * Tests if this reference object is in its associated queue, if any.
431      * This method returns {@code true} only if all of the following conditions
432      * are met:
433      * <ul>
434      * <li>this reference object was registered with a queue when it was created; and
435      * <li>the garbage collector has added this reference object to the queue
436      *     or {@link #enqueue()} is called; and
437      * <li>this reference object is not yet removed from the queue.
438      * </ul>
439      * Otherwise, this method returns {@code false}.
440      * This method may return {@code false} if this reference object has been cleared
441      * but not enqueued due to the race condition.
442      *
443      * @deprecated
444      * This method was originally specified to test if a reference object has
445      * been cleared and enqueued but was never implemented to do this test.
446      * This method could be misused due to the inherent race condition
447      * or without an associated {@code ReferenceQueue}.
448      * An application relying on this method to release critical resources
449      * could cause serious performance issue.
450      * An application should use {@link ReferenceQueue} to reliably determine
451      * what reference objects that have been enqueued or
452      * {@link #refersTo(Object) refersTo(null)} to determine if this reference
453      * object has been cleared.
454      *
455      * @return   {@code true} if and only if this reference object is
456      *           in its associated queue (if any).
457      */
458     @Deprecated(since="16")
459     public boolean isEnqueued() {
460         return (this.queue == ReferenceQueue.ENQUEUED);
461     }
462 
463     /**
464      * Clears this reference object and adds it to the queue with which
465      * it is registered, if any.
466      *
467      * <p> This method is invoked only by Java code; when the garbage collector
468      * enqueues references it does so directly, without invoking this method.
469      *
470      * @return   {@code true} if this reference object was successfully
471      *           enqueued; {@code false} if it was already enqueued or if
472      *           it was not registered with a queue when it was created
473      */
474     public boolean enqueue() {
475         clear0();               // Intentionally clear0() rather than clear()
476         return this.queue.enqueue(this);
477     }
478 
479     /**
480      * Throws {@link CloneNotSupportedException}. A {@code Reference} cannot be
481      * meaningfully cloned. Construct a new {@code Reference} instead.
482      *
483      * @return never returns normally
484      * @throws  CloneNotSupportedException always
485      *
486      * @since 11
487      */
488     @Override
489     protected Object clone() throws CloneNotSupportedException {
490         throw new CloneNotSupportedException();
491     }
492 
493     /* -- Constructors -- */
494 
495     Reference(T referent) {
496         this(referent, null);
497     }
498 
499     Reference(T referent, ReferenceQueue<? super T> queue) {
500         if (referent != null && referent.getClass().isPrimitiveClass()) {
501             throw new IllegalArgumentException("cannot reference a primitive type: " +
502                     referent.getClass().getName());
503         }
504         this.referent = referent;
505         this.queue = (queue == null) ? ReferenceQueue.NULL : queue;
506     }
507 
508     /**
509      * Ensures that the object referenced by the given reference remains
510      * <a href="package-summary.html#reachability"><em>strongly reachable</em></a>,
511      * regardless of any prior actions of the program that might otherwise cause
512      * the object to become unreachable; thus, the referenced object is not
513      * reclaimable by garbage collection at least until after the invocation of
514      * this method.  Invocation of this method does not itself initiate garbage
515      * collection or finalization.
516      *
517      * <p> This method establishes an ordering for <em>strong reachability</em>
518      * with respect to garbage collection.  It controls relations that are
519      * otherwise only implicit in a program -- the reachability conditions
520      * triggering garbage collection.  This method is designed for use in
521      * uncommon situations of premature finalization where using
522      * {@code synchronized} blocks or methods, or using other synchronization
523      * facilities are not possible or do not provide the desired control.  This
524      * method is applicable only when reclamation may have visible effects,
525      * which is possible for objects with finalizers (See Section {@jls 12.6}
526      * of <cite>The Java Language Specification</cite>) that
527      * are implemented in ways that rely on ordering control for
528      * correctness.
529      *
530      * @apiNote
531      * Finalization may occur whenever the virtual machine detects that no
532      * reference to an object will ever be stored in the heap: The garbage
533      * collector may reclaim an object even if the fields of that object are
534      * still in use, so long as the object has otherwise become unreachable.
535      * This may have surprising and undesirable effects in cases such as the
536      * following example in which the bookkeeping associated with a class is
537      * managed through array indices.  Here, method {@code action} uses a
538      * {@code reachabilityFence} to ensure that the {@code Resource} object is
539      * not reclaimed before bookkeeping on an associated
540      * {@code ExternalResource} has been performed; in particular here, to
541      * ensure that the array slot holding the {@code ExternalResource} is not
542      * nulled out in method {@link Object#finalize}, which may otherwise run
543      * concurrently.
544      *
545      * <pre> {@code
546      * class Resource {
547      *   private static ExternalResource[] externalResourceArray = ...
548      *
549      *   int myIndex;
550      *   Resource(...) {
551      *     myIndex = ...
552      *     externalResourceArray[myIndex] = ...;
553      *     ...
554      *   }
555      *   protected void finalize() {
556      *     externalResourceArray[myIndex] = null;
557      *     ...
558      *   }
559      *   public void action() {
560      *     try {
561      *       // ...
562      *       int i = myIndex;
563      *       Resource.update(externalResourceArray[i]);
564      *     } finally {
565      *       Reference.reachabilityFence(this);
566      *     }
567      *   }
568      *   private static void update(ExternalResource ext) {
569      *     ext.status = ...;
570      *   }
571      * }}</pre>
572      *
573      * Here, the invocation of {@code reachabilityFence} is nonintuitively
574      * placed <em>after</em> the call to {@code update}, to ensure that the
575      * array slot is not nulled out by {@link Object#finalize} before the
576      * update, even if the call to {@code action} was the last use of this
577      * object.  This might be the case if, for example a usage in a user program
578      * had the form {@code new Resource().action();} which retains no other
579      * reference to this {@code Resource}.  While probably overkill here,
580      * {@code reachabilityFence} is placed in a {@code finally} block to ensure
581      * that it is invoked across all paths in the method.  In a method with more
582      * complex control paths, you might need further precautions to ensure that
583      * {@code reachabilityFence} is encountered along all of them.
584      *
585      * <p> It is sometimes possible to better encapsulate use of
586      * {@code reachabilityFence}.  Continuing the above example, if it were
587      * acceptable for the call to method {@code update} to proceed even if the
588      * finalizer had already executed (nulling out slot), then you could
589      * localize use of {@code reachabilityFence}:
590      *
591      * <pre> {@code
592      * public void action2() {
593      *   // ...
594      *   Resource.update(getExternalResource());
595      * }
596      * private ExternalResource getExternalResource() {
597      *   ExternalResource ext = externalResourceArray[myIndex];
598      *   Reference.reachabilityFence(this);
599      *   return ext;
600      * }}</pre>
601      *
602      * <p> Method {@code reachabilityFence} is not required in constructions
603      * that themselves ensure reachability.  For example, because objects that
604      * are locked cannot, in general, be reclaimed, it would suffice if all
605      * accesses of the object, in all methods of class {@code Resource}
606      * (including {@code finalize}) were enclosed in {@code synchronized (this)}
607      * blocks.  (Further, such blocks must not include infinite loops, or
608      * themselves be unreachable, which fall into the corner case exceptions to
609      * the "in general" disclaimer.)  However, method {@code reachabilityFence}
610      * remains a better option in cases where this approach is not as efficient,
611      * desirable, or possible; for example because it would encounter deadlock.
612      *
613      * @param ref the reference. If {@code null}, this method has no effect.
614      * @since 9
615      */
616     @ForceInline
617     public static void reachabilityFence(Object ref) {
618         // Does nothing. This method is annotated with @ForceInline to eliminate
619         // most of the overhead that using @DontInline would cause with the
620         // HotSpot JVM, when this fence is used in a wide variety of situations.
621         // HotSpot JVM retains the ref and does not GC it before a call to
622         // this method, because the JIT-compilers do not have GC-only safepoints.
623     }
624 }