public class Finalizer extends ReferenceQueue implements Runnable
This is singleton class and its instance can be accessed as Finalizer.INSTANCE
you can tell Finalizer to execute given runnable when a particular
object gets garbage collected:
Object myObject = ...;
Finalizer.INSTANCE.track(myObject, new Runnable(){
public void run(){
System.out.println("myObject is garbage collected");
}
});
Finalizer creates a WeakReference for the object that needs to
be tracked. you can also tell which type of Reference to use as below:
Object myObject = ...; Finalizer.INSTANCE.All thetrack(myObject,SoftReference.class, new Runnable(){ public void run(){ System.out.println("myObject is garbage collected"); } });
track(...) methods return the Reference object created.
You can also use Finalizer as a simple profiler.
Object myObject = ...;
Finalizer.INSTANCE.trackGC(myObject, "myObject is garbage collected");
the above code says to print "myObject is garbage collected" to console, when myObject gets
garbage collected.
This class starts a Thread named "JLibsFinalizer with Thread.MIN_PRIORITY
| Modifier and Type | Method and Description |
|---|---|
void |
run() |
<T,R extends Reference<T>> |
track(T obj,
Class<R> type,
Runnable runnable)
tracks the given
obj using specified reference type.Specified runnable is executed when obj gets garbage collected. |
<T> WeakReference<T> |
track(T obj,
Runnable runnable)
tracks the given
obj using WeakReference.Specified runnable is executed when obj gets garbage collected. |
void |
trackGC(Object obj)
Prints message to
System.out when obj gets garbage collected. |
void |
trackGC(Object obj,
String message)
Prints
message to System.out when obj gets garbage collected |
poll, remove, removepublic static final Finalizer INSTANCE
public <T> WeakReference<T> track(T obj, Runnable runnable)
obj using WeakReference.runnable is executed when obj gets garbage collected.obj - object needs to be trackedrunnable - runnable to be executed when obj gets garbage collectedWeakReference created for objtrack(Object, Class, Runnable)public <T,R extends Reference<T>> R track(T obj, Class<R> type, Runnable runnable)
obj using specified reference type.runnable is executed when obj gets garbage collected.obj - object needs to be trackedtype - type of reference to be used for trackingrunnable - runnable to be executed when obj gets garbage collectedReference created for objtrack(Object, Runnable)public void trackGC(Object obj)
System.out when obj gets garbage collected.
The message will be obj.getClass().getName()+'@'+System.identityHashCode(obj)
obj - object needs to be trackedtrackGC(Object, String)public void trackGC(Object obj, String message)
message to System.out when obj gets garbage collectedobj - object needs to be trackedmessage - message to be printed when obj gets garbage collected.
if null, the message will be obj.getClass().getName()+'@'+System.identityHashCode(obj)Copyright © 2021. All rights reserved.