Class Reference<T>

java.lang.Object
java.lang.ref.Reference<T>
Type Parameters:
T - the type of the referent
Direct Known Subclasses:
PhantomReference,SoftReference,WeakReference

public abstract sealed classReference<T>extendsObjectpermitsPhantomReference<T>,SoftReference<T>,WeakReference<T>(not exhaustive)
Abstract base class for reference objects. This class defines theoperations common to all reference objects. Because reference objects areimplemented in close cooperation with the garbage collector, this class maynot be subclassed directly.
Sealed Class Hierarchy Graph:
Sealed class hierarchy graph for ReferenceSealed class hierarchy graph for Reference
Since:
1.2
  • Method Details

    • get

      public T get()
      Returns this reference object's referent. If this reference object hasbeen cleared, either by the program or by the garbage collector, thenthis method returnsnull.
      API Note:
      This method returns a strong reference to the referent. This may causethe garbage collector to treat it as strongly reachable until some latercollection cycle. TherefersTo method can beused to avoid such strengthening when testing whether some object isthe referent of a reference object; that is, useref.refersTo(obj)rather thanref.get() == obj.
      Returns:
      The object to which this reference refers, ornull if this reference object has been cleared
      See Also:
    • refersTo

      public final boolean refersTo(T obj)
      Tests if the referent of this reference object isobj.Using anullobj returnstrue if thereference object has been cleared.
      Parameters:
      obj - the object to compare with this reference object's referent
      Returns:
      true ifobj is the referent of this reference object
      Since:
      16
    • clear

      public void clear()
      Clears this reference object. Invoking this method does not enqueue thisobject, and the garbage collector will not clear or enqueue this object.

      When the garbage collector or theenqueue() method clearreferences they do so directly, without invoking this method.

      API Note:
      There is a potential race condition with the garbage collector. When thismethod is called, the garbage collector may already be in the process of(or already completed) clearing and/or enqueueing this reference.Avoid this race by ensuring the referent remains strongly reachable untilafter the call to clear(), usingreachabilityFence(Object) ifnecessary.
    • isEnqueued

      @Deprecated(since="16")public boolean isEnqueued()
      Deprecated.
      This method was originally specified to test if a reference object hasbeen cleared and enqueued but was never implemented to do this test.This method could be misused due to the inherent race conditionor without an associatedReferenceQueue.An application relying on this method to release critical resourcescould cause serious performance issue.An application should useReferenceQueue to reliably determinewhat reference objects that have been enqueued orrefersTo(null) to determine if this referenceobject has been cleared.
      Tests if this reference object is in its associated queue, if any.This method returnstrue only if all of the following conditionsare met:
      • this reference object was registered with a queue when it was created; and
      • the garbage collector has added this reference object to the queue orenqueue() is called; and
      • this reference object is not yet removed from the queue.
      Otherwise, this method returnsfalse.This method may returnfalse if this reference object has been clearedbut not enqueued due to the race condition.
      Returns:
      true if and only if this reference object is in its associated queue (if any).
    • enqueue

      public boolean enqueue()
      Clears this reference object, then attempts to add it to the queue withwhich it is registered, if any.

      If this reference is registered with a queue but not yet enqueued,the reference is added to the queue; this method issuccessful and returns true.If this reference is not registered with a queue, or was already enqueued(by the garbage collector, or a previous call toenqueue), thismethod isunsuccessful and returns false.

      Memory consistency effects:Actions in a thread prior to asuccessful call toenqueuehappen-beforethe reference is removed from the queue byReferenceQueue.poll()orReferenceQueue.remove(long).Unsuccessful calls toenqueue have no specified memory consistency effects.

      When this method clears references it does so directly, withoutinvoking theclear() method. When the garbage collector clearsand enqueues references it does so directly, without invoking theclear() method or this method.

      API Note:
      Use of this method allows the registered queue'sReferenceQueue.poll() andReferenceQueue.remove(long) methodsto return this reference even though the referent may still be stronglyreachable.
      Returns:
      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
    • clone

      protected Object clone() throwsCloneNotSupportedException
      ThrowsCloneNotSupportedException. AReference cannot bemeaningfully cloned. Construct a newReference instead.
      Overrides:
      clone in class Object
      Returns:
      never returns normally
      Throws:
      CloneNotSupportedException - always
      See Also:
    • reachabilityFence

      public static void reachabilityFence(Object ref)
      Ensures that the given object remainsstrongly reachable.This reachability is assured regardless of any optimizing transformationsthe virtual machine may perform that might otherwise allow the object tobecome unreachable (see JLS12.6.1). Thus, the given object is notreclaimable by garbage collection at least until after the invocation ofthis method. References to the given object will not be cleared (orenqueued, if applicable) by the garbage collector until after invocationof this method.Invocation of this method does not itself initiate reference processing,garbage collection, or finalization.

      This method establishes an ordering forstrong reachabilitywith respect to garbage collection. It controls relations that areotherwise only implicit in a program -- the reachability conditionstriggering garbage collection. This method is applicable onlywhen reclamation may have visible effects,such as for objects that use finalizers orCleaner, or code thatperformsreference processing.

      Memory consistency effects:Actions in a thread prior to callingreachabilityFence(x)happen-beforethe garbage collector clears any reference tox.

      API Note:
      Reference processing or finalization can occur after an object becomesunreachable. An object can become unreachable when the virtual machinedetects that there is no further need for the object (other than forrunning a finalizer). In the course of optimization, the virtual machinecan reorder operations of an object's methods such that the objectbecomes unneeded earlier than might naively be expected —including while a method of the object is still running. For instance,the VM can move the loading ofvalues from the object's fieldsto occur earlier. The object itself is then no longer needed and becomesunreachable, and the method can continue running using the obtained values.This may have surprising and undesirable effects when using a Cleaner orfinalizer for cleanup: there is a race between theprogram thread running the method, and the cleanup thread running theCleaner or finalizer. The cleanup thread could free aresource, followed by the program thread (still running the method)attempting to access the now-already-freed resource.Use ofreachabilityFence can prevent this race by ensuring that theobject remains strongly reachable.

      The following is an example in which the bookkeeping associated with a class ismanaged through array indices. Here, methodaction uses areachabilityFence to ensure that theResource object isnot reclaimed before bookkeeping on an associatedExternalResource has been performed; specifically, toensure that the array slot holding theExternalResource is notnulled out in methodObject.finalize(), which may otherwise runconcurrently.

      class Resource {  private static ExternalResource[] externalResourceArray = ...  int myIndex;  Resource(...) {    this.myIndex = ...    externalResourceArray[myIndex] = ...;    ...  }  protected void finalize() {    externalResourceArray[this.myIndex] = null;    ...  }  public void action() {    try {      // ...      int i = this.myIndex; // last use of 'this' Resource in action()      Resource.update(externalResourceArray[i]);    } finally {      Reference.reachabilityFence(this);    }  }  private static void update(ExternalResource ext) {    ext.status = ...;  }}
      The invocation ofreachabilityFence isplacedafter the call toupdate, to ensure that thearray slot is not nulled out byObject.finalize() before theupdate, even if the call toaction was the last use of thisobject. This might be the case if, for example, a usage in a user programhad the formnew Resource().action(); which retains no otherreference to thisResource.ThereachabilityFence call is placed in afinally block toensure that it is invoked across all paths in the method. A more complexmethod might need further precautions to ensure thatreachabilityFence is encountered along all code paths.

      MethodreachabilityFence is not required in constructionsthat themselves ensure reachability. For example, because objects thatare locked cannot, in general, be reclaimed, it would suffice if allaccesses of the object, in all methods of classResource(includingfinalize) were enclosed insynchronized (this)blocks. (Further, such blocks must not include infinite loops, orthemselves be unreachable, which fall into the corner case exceptions tothe "in general" disclaimer.) However, methodreachabilityFenceremains a better option in cases where synchronization is not as efficient,desirable, or possible; for example because it would encounter deadlock.

      Parameters:
      ref - the reference to the object to keep strongly reachable. Ifnull, this method has no effect.
      Since:
      9