Package com.google.common.base
Class FinalizableReferenceQueue
- java.lang.Object
-
- com.google.common.base.FinalizableReferenceQueue
-
- All Implemented Interfaces:
Closeable
,AutoCloseable
@GwtIncompatible public class FinalizableReferenceQueue extends Object implements Closeable
A reference queue with an associated background thread that dequeues references and invokesFinalizableReference.finalizeReferent()
on them. Java 9+ users should preferCleaner
; see example below.Keep a strong reference to this object until all of the associated referents have been finalized. If this object is garbage collected earlier, the backing thread will not invoke
finalizeReferent()
on the remaining references.As an example of how this is used, imagine you have a class
MyServer
that creates aServerSocket
, and you would like to ensure that theServerSocket
is closed even if theMyServer
object is garbage-collected without calling itsclose
method. You could use a finalizer to accomplish this, but that has a number of well-known problems. Here is how you might use this class instead:{@code public class MyServer implements Closeable { private static final FinalizableReferenceQueue frq = new FinalizableReferenceQueue(); // You might also share this between several objects. private static final Set
> references = Sets.newConcurrentHashSet(); // This ensures that the FinalizablePhantomReference itself is not garbage-collected. private final ServerSocket serverSocket; private MyServer(...) { ... this.serverSocket = new ServerSocket(...); ... } public static MyServer create(...) { MyServer myServer = new MyServer(...); ServerSocket serverSocket = myServer.serverSocket; Reference> reference = new FinalizablePhantomReference (myServer, frq) { - Since:
- 2.0
- Author:
- Bob Lee
-
-
Constructor Summary
Constructors Constructor Description FinalizableReferenceQueue()
Constructs a new queue.
-
-
-
Constructor Detail
-
FinalizableReferenceQueue
public FinalizableReferenceQueue()
Constructs a new queue.
-
-
Method Detail
-
close
public void close()
- Specified by:
close
in interfaceAutoCloseable
- Specified by:
close
in interfaceCloseable
-
-