Class Reference<T>
- Type Parameters:
T- the type of the referent
- Direct Known Subclasses:
PhantomReference, SoftReference, WeakReference
public abstract sealed class Reference<T> extends Object permits PhantomReference<T>, SoftReference<T>, WeakReference<T> (not exhaustive)
Method Summary
| Modifier and Type | Method | Description |
|---|---|---|
void |
clear() |
Clears this reference object. |
protected Object |
clone() |
Throws CloneNotSupportedException. |
boolean |
enqueue() |
Clears this reference object, then attempts to add it to the queue with which it is registered, if any. |
T |
get() |
Returns this reference object's referent. |
boolean |
isEnqueued() |
Deprecated. This method was originally specified to test if a reference object has been cleared and enqueued but was never implemented to do this test. |
static void |
reachabilityFence |
Ensures that the given object remains strongly reachable. |
final boolean |
refersTo |
Tests if the referent of this reference object is obj. |
Methods declared in class Object
equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait | Modifier and Type | Method | Description |
|---|---|---|
boolean |
equals |
Indicates whether some other object is "equal to" this one. |
protected void |
finalize() |
Deprecated, for removal: This API element is subject to removal in a future version. Finalization is deprecated and subject to removal in a future release. |
final Class |
getClass() |
Returns the runtime class of this Object. |
int |
hashCode() |
Returns a hash code value for this object. |
final void |
notify() |
Wakes up a single thread that is waiting on this object's monitor. |
final void |
notifyAll() |
Wakes up all threads that are waiting on this object's monitor. |
String |
toString() |
Returns a string representation of the object. |
final void |
wait() |
Causes the current thread to wait until it is awakened, typically by being notified or interrupted. |
final void |
wait |
Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed. |
final void |
wait |
Causes the current thread to wait until it is awakened, typically by being notified or interrupted, or until a certain amount of real time has elapsed. |
Method Details
get
public T get()
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
refersTomethod can be used to avoid such strengthening when testing whether some object is the referent of a reference object; that is, useref.refersTo(obj)rather thanref.get() == obj. - Returns:
- The object to which this reference refers, or
nullif this reference object has been cleared - See Also:
refersTo
public final boolean refersTo(T obj)
obj. Using a null obj returns true if the reference object has been cleared.- Parameters:
-
obj- the object to compare with this reference object's referent - Returns:
-
trueifobjis the referent of this reference object - Since:
- 16
clear
public void clear()
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.
isEnqueued
@Deprecated(since="16") public boolean isEnqueued()
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.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.
false. This method may return false if this reference object has been cleared but not enqueued due to the race condition.- Returns:
-
trueif and only if this reference object is in its associated queue (if any).
enqueue
public boolean enqueue()
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(long). 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()andReferenceQueue.remove(long)methods to return this reference even though the referent may still be strongly reachable. - Returns:
-
trueif this reference object was successfully enqueued;falseif it was already enqueued or if it was not registered with a queue when it was created
clone
protected Object clone() throws CloneNotSupportedException
CloneNotSupportedException. A Reference cannot be meaningfully cloned. Construct a new Reference instead.- Overrides:
-
clonein classObject - Returns:
- never returns normally
- Throws:
-
CloneNotSupportedException- always - See Also:
reachabilityFence
public static void reachabilityFence(Object ref)
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
reachabilityFencecan 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
actionuses areachabilityFenceto ensure that theResourceobject is not reclaimed before bookkeeping on an associatedExternalResourcehas been performed; specifically, to ensure that the array slot holding theExternalResourceis not nulled out in methodObject.finalize(), which may otherwise run concurrently.The invocation ofclass 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 = ...; } }reachabilityFenceis placed after the call toupdate, to ensure that the array slot is not nulled out byObject.finalize()before the update, even if the call toactionwas the last use of this object. This might be the case if, for example, a usage in a user program had the formnew Resource().action();which retains no other reference to thisResource. ThereachabilityFencecall is placed in afinallyblock to ensure that it is invoked across all paths in the method. A more complex method might need further precautions to ensure thatreachabilityFenceis encountered along all code paths.Method
reachabilityFenceis 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 classResource(includingfinalize) were enclosed insynchronized (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, 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
© 1993, 2025, Oracle and/or its affiliates. All rights reserved.
Documentation extracted from Debian's OpenJDK Development Kit package.
Licensed under the GNU General Public License, version 2, with the Classpath Exception.
Various third party code in OpenJDK is licensed under different licenses (see Debian package).
Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.