Java Reference
In-Depth Information
public
public void
void setClosed () {
closed = true
true ;
doNativeCleanup ();
}
public
public void
void cleanup () {
iif (! closed ) {
doNativeCleanup ();
}
}
private
private native
native void
void allocateNative ();
private
private native
native void
void doNativeCleanup ();
}
Here is the outline of such a class, which uses a weak reference. The constructor here alloc-
ates some native resource. Under normal usage, the setClosed() method is expected to be
called; that will clean up the native memory.
However, the weak reference is also placed on a reference queue. When the reference is
pulled from the queue, it can check to make sure the native memory has been cleaned up
(and clean it if it has not).
Processing of the reference queue happens in a daemon thread:
static
static {
finRefQueue = new
new ReferenceQueue <>();
Runnable r = new
new Runnable () {
public
public void
void run () {
CleanupFinalizer fr ;
while
while ( true
true ) {
try
try {
fr = ( CleanupFinalizer ) finRefQueue . remove ();
fr . cleanup ();
pendingRefs . remove ( fr );
} catch
catch ( Exception ex ) {
Logger . getLogger (
CleanupFinalizer . class . getName ()).
log ( Level . SEVERE , null
null , ex );
}
}
}
};
Search WWH ::




Custom Search