Top Description Inners Fields Constructors Methods
java.lang.ref

public abstract sealed Class Reference<T>

extends Object
permits PhantomReference<T>, SoftReference<T>, WeakReference<T>, FinalReference<T>
Class Inheritance
Known Direct Subclasses
java.lang.ref.SoftReference, java.lang.ref.WeakReference, java.lang.ref.FinalReference, java.lang.ref.PhantomReference
Type Parameters
<T>
the type of the referent
Imports
jdk.internal.misc.Unsafe, jdk.internal.vm.annotation.ForceInline, .IntrinsicCandidate, jdk.internal.access.JavaLangRefAccess, .SharedSecrets, jdk.internal.ref.Cleaner

Abstract base class for reference objects. This class defines the operations common to all reference objects. Because reference objects are implemented in close cooperation with the garbage collector, this class may not be subclassed directly.
Author
Mark Reinhold
Since
1.2

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class

Field Summary

Modifier and TypeField and Description
private transient Reference<?>
pack-priv volatile Reference<T>
private static boolean
private static final Object
pack-priv volatile ReferenceQueue<? super T>
private T

Constructor Summary

AccessConstructor and Description
pack-priv
Reference(T referent)

pack-priv
Reference(T referent, ReferenceQueue<? super T> queue)

Method Summary

Modifier and TypeMethod and Description
public void
clear()

Clears this reference object.

private native void
pack-priv void
clearInactiveFinalReference()

Clear referent with strong semantics.

protected Object

Returns:

never returns normally
clone
()

Overrides java.lang.Object.clone.

Throws CloneNotSupportedException.

public boolean

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
enqueue
()

Clears this reference object, then attempts to add it to the queue with which it is registered, if any.

private void
public T

Returns:

The object to which this reference refers, or null if this reference object has been cleared
get
()

Returns this reference object's referent.

private static native Reference<?>
pack-priv T
getFromInactiveFinalReference()

Load referent with strong semantics.

private static native boolean
public boolean

Returns:

true if and only if this reference object is in its associated queue (if any).
isEnqueued
()
Deprecated since 16. This method was originally specified to test if a reference object has been cleared and enqueued but was never implemented to do this test.

Tests if this reference object is in its associated queue, if any.

private static void
public static void
reachabilityFence(Object
the reference to the object to keep strongly reachable. If null, this method has no effect.
ref
)

Ensures that the given object remains strongly reachable.

public final boolean

Returns:

true if obj is the referent of this reference object
refersTo
(T
the object to compare with this reference object's referent
obj
)

Tests if the referent of this reference object is obj.

private native boolean
pack-priv boolean
refersToImpl(T obj)

pack-priv static void
startReferenceHandlerThread(ThreadGroup tg)

Start the Reference Handler thread as a daemon thread.

private static native void
private static boolean
Inherited from java.lang.Object:
equalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

discoveredback to summary
private transient Reference<?> discovered
nextback to summary
pack-priv volatile Reference<T> next
Annotations
@SuppressWarnings:rawtypes
processPendingActiveback to summary
private static boolean processPendingActive
processPendingLockback to summary
private static final Object processPendingLock
queueback to summary
pack-priv volatile ReferenceQueue<? super T> queue
referentback to summary
private T referent

Constructor Detail

Referenceback to summary
pack-priv Reference(T referent)
Referenceback to summary
pack-priv Reference(T referent, ReferenceQueue<? super T> queue)

Method Detail

clearback to summary
public void clear()

Clears this reference object. Invoking this method does not enqueue this object, and the garbage collector will not clear or enqueue this object.

When the garbage collector or the enqueue() method clear references they do so directly, without invoking this method.

API Note

There is a potential race condition with the garbage collector. When this method 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 until after the call to clear(), using reachabilityFence(Object) if necessary.

clear0back to summary
private native void clear0()
clearInactiveFinalReferenceback to summary
pack-priv void clearInactiveFinalReference()

Clear referent with strong semantics.

cloneback to summary
protected Object clone() throws CloneNotSupportedException

Overrides java.lang.Object.clone.

Throws CloneNotSupportedException. A Reference cannot be meaningfully cloned. Construct a new Reference instead.

Returns:Object

never returns normally

Annotations
@Override
Exceptions
CloneNotSupportedException:
always
Since
11
enqueueback to summary
public boolean enqueue()

Clears this reference object, then attempts to add it to the queue with which 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 is successful and returns true. If this reference is not registered with a queue, or was already enqueued (by the garbage collector, or a previous call to enqueue), this method is unsuccessful and returns false.

Memory consistency effects: Actions in a thread prior to a successful call to enqueue happen-before the reference is removed from the queue by ReferenceQueue#poll or ReferenceQueue#remove. Unsuccessful calls to enqueue have no specified memory consistency effects.

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

API Note

Use of this method allows the registered queue's ReferenceQueue#poll and ReferenceQueue#remove methods to return this reference even though the referent may still be strongly reachable.

Returns:boolean

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

enqueueFromPendingback to summary
private void enqueueFromPending()
getback to summary
public T get()

Returns this reference object's referent. If this reference object has been cleared, either by the program or by the garbage collector, then this method returns null.

API Note

This method returns a strong reference to the referent. This may cause the garbage collector to treat it as strongly reachable until some later collection cycle. The refersTo method can be used to avoid such strengthening when testing whether some object is the referent of a reference object; that is, use ref.refersTo(obj) rather than ref.get() == obj.

Returns:T

The object to which this reference refers, or null if this reference object has been cleared

Annotations
@IntrinsicCandidate
See Also
refersTo
getAndClearReferencePendingListback to summary
private static native Reference<?> getAndClearReferencePendingList()
getFromInactiveFinalReferenceback to summary
pack-priv T getFromInactiveFinalReference()

Load referent with strong semantics.

hasReferencePendingListback to summary
private static native boolean hasReferencePendingList()
isEnqueuedback to summary
public boolean isEnqueued()

Deprecated

since 16.

This method was originally specified to test if a reference object has been cleared and enqueued but was never implemented to do this test. This method could be misused due to the inherent race condition or without an associated ReferenceQueue. An application relying on this method to release critical resources could cause serious performance issue. An application should use ReferenceQueue to reliably determine what reference objects that have been enqueued or refersTo(null) to determine if this reference object has been cleared.

Tests if this reference object is in its associated queue, if any. This method returns true only if all of the following conditions are 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 or enqueue() is called; and
  • this reference object is not yet removed from the queue.
Otherwise, this method returns false. This method may return false if this reference object has been cleared but not enqueued due to the race condition.
Returns:boolean

true if and only if this reference object is in its associated queue (if any).

Annotations
@Deprecated
since:16
processPendingReferencesback to summary
private static void processPendingReferences()
reachabilityFenceback to summary
public static void reachabilityFence(Object ref)

Ensures that the given object remains strongly reachable. This reachability is assured regardless of any optimizing transformations the virtual machine may perform that might otherwise allow the object to become unreachable (see JLS 12.6.1). Thus, the given object is not reclaimable by garbage collection at least until after the invocation of this method. References to the given object will not be cleared (or enqueued, if applicable) by the garbage collector until after invocation of this method. Invocation of this method does not itself initiate reference processing, garbage collection, or finalization.

This method establishes an ordering for strong reachability with respect to garbage collection. It controls relations that are otherwise only implicit in a program -- the reachability conditions triggering garbage collection. This method is applicable only when reclamation may have visible effects, such as for objects that use finalizers or Cleaner, or code that performs reference processing.

Memory consistency effects: Actions in a thread prior to calling reachabilityFence(x) happen-before the garbage collector clears any reference to x.

API Note

Reference processing or finalization can occur after an object becomes unreachable. An object can become unreachable when the virtual machine detects that there is no further need for the object (other than for running a finalizer). In the course of optimization, the virtual machine can reorder operations of an object's methods such that the object becomes 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 of values from the object's fields to occur earlier. The object itself is then no longer needed and becomes unreachable, and the method can continue running using the obtained values. This may have surprising and undesirable effects when using a Cleaner or finalizer for cleanup: there is a race between the program thread running the method, and the cleanup thread running the Cleaner or finalizer. The cleanup thread could free a resource, followed by the program thread (still running the method) attempting to access the now-already-freed resource. Use of reachabilityFence can prevent this race by ensuring that the object remains strongly reachable.

The following is an example in which the bookkeeping associated with a class is managed through array indices. Here, method action uses a reachabilityFence to ensure that the Resource object is not reclaimed before bookkeeping on an associated ExternalResource has been performed; specifically, to ensure that the array slot holding the ExternalResource is not nulled out in method Object#finalize, which may otherwise run concurrently.

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 = ...; } }
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 of reachabilityFence is placed after the call to update, to ensure that the array slot is not nulled out by Object#finalize before the update, even if the call to action was the last use of this object. This might be the case if, for example, a usage in a user program had the form new Resource().action(); which retains no other reference to this Resource. The reachabilityFence call is placed in a finally block to ensure that it is invoked across all paths in the method. A more complex method might need further precautions to ensure that reachabilityFence is encountered along all code paths.

Method reachabilityFence is not required in constructions that themselves ensure reachability. For example, because objects that are locked cannot, in general, be reclaimed, it would suffice if all accesses of the object, in all methods of class Resource (including finalize) were enclosed in synchronized (this) blocks. (Further, such blocks must not include infinite loops, or themselves be unreachable, which fall into the corner case exceptions to the "in general" disclaimer.) However, method reachabilityFence remains a better option in cases where synchronization is not as efficient, desirable, or possible; for example because it would encounter deadlock.

Parameters
ref:Object

the reference to the object to keep strongly reachable. If null, this method has no effect.

Annotations
@ForceInline
Since
9
refersToback to summary
public final boolean refersTo(T obj)

Tests if the referent of this reference object is obj. Using a null obj returns true if the reference object has been cleared.

Parameters
obj:T

the object to compare with this reference object's referent

Returns:boolean

true if obj is the referent of this reference object

Since
16
refersTo0back to summary
private native boolean refersTo0(Object o)
Annotations
@IntrinsicCandidate
refersToImplback to summary
pack-priv boolean refersToImpl(T obj)
startReferenceHandlerThreadback to summary
pack-priv static void startReferenceHandlerThread(ThreadGroup tg)

Start the Reference Handler thread as a daemon thread.

waitForReferencePendingListback to summary
private static native void waitForReferencePendingList()
waitForReferenceProcessingback to summary
private static boolean waitForReferenceProcessing() throws InterruptedException
java.lang.ref back to summary

private Class Reference.ReferenceHandler

extends Thread
Class Inheritance

Field Summary

Inherited from java.lang.Thread:
MAX_PRIORITYMIN_PRIORITYNORM_PRIORITY

Constructor Summary

AccessConstructor and Description
pack-priv

Method Summary

Modifier and TypeMethod and Description
public void
run()

Overrides java.lang.Thread.run.

Implements java.lang.Runnable.run.

This method is run by the thread when it executes.

Inherited from java.lang.Thread:
activeCountcheckAccessclonecurrentThreaddumpStackenumerategetAllStackTracesgetContextClassLoadergetDefaultUncaughtExceptionHandlergetIdgetNamegetPrioritygetStackTracegetStategetThreadGroupgetUncaughtExceptionHandlerholdsLockinterruptinterruptedisAliveisDaemonisInterruptedisVirtualjoinjoinjoinjoinofPlatformofVirtualonSpinWaitsetContextClassLoadersetDaemonsetDefaultUncaughtExceptionHandlersetNamesetPrioritysetUncaughtExceptionHandlersleepsleepsleepstartstartVirtualThreadstopthreadIdtoStringyield

Constructor Detail

ReferenceHandlerback to summary
pack-priv ReferenceHandler(ThreadGroup g, String name)

Method Detail

runback to summary
public void run()

Overrides java.lang.Thread.run.

Implements java.lang.Runnable.run.

Doc from java.lang.Thread.run.

This method is run by the thread when it executes. Subclasses of Thread may override this method.

This method is not intended to be invoked directly. If this thread is a platform thread created with a Runnable task then invoking this method will invoke the task's run method. If this thread is a virtual thread then invoking this method directly does nothing.