Cleaner
manages a set of object references and corresponding cleaning actions.
Cleaning actions are registered
to run after the cleaner is notified that the object has become phantom reachable. The cleaner uses PhantomReference
and ReferenceQueue
to be notified when the reachability changes.
Each cleaner operates independently, managing the pending cleaning actions and handling threading and termination when the cleaner is no longer in use. Registering an object reference and corresponding cleaning action returns a Cleanable
. The most efficient use is to explicitly invoke the clean
method when the object is closed or no longer needed. The cleaning action is a Runnable
to be invoked at most once when the object has become phantom reachable unless it has already been explicitly cleaned. Note that the cleaning action must not refer to the object being registered. If so, the object will not become phantom reachable and the cleaning action will not be invoked automatically.
The execution of the cleaning action is performed by a thread associated with the cleaner. All exceptions thrown by the cleaning action are ignored. The cleaner and other cleaning actions are not affected by exceptions in a cleaning action. The thread runs until all registered cleaning actions have completed and the cleaner itself is reclaimed by the garbage collector.
The behavior of cleaners during System.exit
is implementation specific. No guarantees are made relating to whether cleaning actions are invoked or not.
Unless otherwise noted, passing a null
argument to a constructor or method in this class will cause a NullPointerException
to be thrown.