public class ReferenceMonitor<T> extends Thread
The usage is the following:
// Initialize the monitor
ReferenceMonitor<SomeType> monitor = new ReferenceMonitor<>();
monitor.start();
// Create your object as usual
SomeType obj = new SomeType();
// Allow the monitor to track `obj` lifecycle, specifying the action to be performed before garbage collection.
monitor.track(obj, () -> {
System.out.println("Performing clean up for `obj`");
});
// Once all references to `obj` are lost, the garbage collector will detect `obj` can be cleared, and the clean up
// action will be performed.
Thread.State, Thread.UncaughtExceptionHandlerMAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY| Constructor and Description |
|---|
ReferenceMonitor()
Creates a reference monitor with default settings.
|
ReferenceMonitor(long millisPause)
Creates a reference monitor.
|
| Modifier and Type | Method and Description |
|---|---|
protected void |
clean(NativeReference<T> ref) |
void |
interrupt() |
void |
run() |
void |
track(T object,
CleanUpAction cleanUpAction)
Associate a clean up action to be performed by this monitor when the object is garbage collected.
|
activeCount, checkAccess, clone, countStackFrames, currentThread, destroy, dumpStack, enumerate, getAllStackTraces, getContextClassLoader, getDefaultUncaughtExceptionHandler, getId, getName, getPriority, getStackTrace, getState, getThreadGroup, getUncaughtExceptionHandler, holdsLock, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setDefaultUncaughtExceptionHandler, setName, setPriority, setUncaughtExceptionHandler, sleep, sleep, start, stop, stop, suspend, toString, yieldpublic ReferenceMonitor()
This is equivalent to calling ReferenceMonitor(long) with millisPause = 50
public ReferenceMonitor(long millisPause)
millisPause - the number of milliseconds the reference monitor will pause its execution if there are no
pending references to clear.public void track(T object, CleanUpAction cleanUpAction)
For the reference monitor to perform the clean up, it is important that the clean up action DOES NOT
CONTAIN any reference to the tracked object.
Failing in this, the object will never be garbage
collected, hence the reference monitor will never run the clean up action.
object - the object to trackcleanUpAction - the action to be performedprotected void clean(NativeReference<T> ref)
Copyright © 2020. All rights reserved.