ReferenceQueue

  • ReferenceQueue is used by the garbage collector to hold registered reference objects after their reachability changes.

  • It provides methods like poll, remove to retrieve these reference objects from the queue.

  • poll is non-blocking and returns immediately with a reference object if available or null otherwise.

  • remove is blocking and waits for a reference object to become available, optionally with a timeout.

  • Using ReferenceQueue, you can be notified about objects becoming eligible for garbage collection and perform cleanup tasks.

public class ReferenceQueue extends Object

Reference queues, to which registered reference objects are appended by the garbage collector after the appropriate reachability changes are detected.

Public Constructor Summary

ReferenceQueue()
Constructs a new reference-object queue.

Public Method Summary

Reference<? extends T>
poll()
Polls this queue to see if a reference object is available.
Reference<? extends T>
remove(long timeout)
Removes the next reference object in this queue, blocking until either one becomes available or the given timeout period expires.
Reference<? extends T>
remove()
Removes the next reference object in this queue, blocking until one becomes available.

Inherited Method Summary

Public Constructors

public ReferenceQueue ()

Constructs a new reference-object queue.

Public Methods

public Reference<? extends T> poll ()

Polls this queue to see if a reference object is available. If one is available without further delay then it is removed from the queue and returned. Otherwise this method immediately returns null.

Returns
  • A reference object, if one was immediately available, otherwise null

public Reference<? extends T> remove (long timeout)

Removes the next reference object in this queue, blocking until either one becomes available or the given timeout period expires.

This method does not offer real-time guarantees: It schedules the timeout as if by invoking the Object.wait(long) method.

Parameters
timeout If positive, block for up to timeout milliseconds while waiting for a reference to be added to this queue. If zero, block indefinitely.
Returns
  • A reference object, if one was available within the specified timeout period, otherwise null
Throws
IllegalArgumentException If the value of the timeout argument is negative
InterruptedException If the timeout wait is interrupted

public Reference<? extends T> remove ()

Removes the next reference object in this queue, blocking until one becomes available.

Returns
  • A reference object, blocking until one becomes available
Throws
InterruptedException If the wait is interrupted