Last active
August 10, 2019 02:48
-
-
Save zencd/bdc8faeb45c3429e26c746efa7be4e1f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.ref.PhantomReference; | |
import java.lang.ref.ReferenceQueue; | |
import java.util.Random; | |
public class PhantomReferenceExample { | |
static class CustomObject { | |
final int externalResourceId = new Random().nextInt(); // any resource descriptor, etc | |
} | |
static class CustomFinalizer extends PhantomReference<CustomObject> { | |
private final int externalResourceId; | |
public CustomFinalizer(CustomObject referent, ReferenceQueue<CustomObject> q) { | |
super(referent, q); | |
// XXX do not store `referent` reference to this! | |
this.externalResourceId = referent.externalResourceId; | |
} | |
public void finalizeResources() { | |
// finish it! | |
System.out.println("freeing resource " + externalResourceId); | |
} | |
} | |
public static void main(String[] args) throws Exception { | |
var referenceQueue = new ReferenceQueue<CustomObject>(); | |
var referent = new CustomObject(); | |
var phantom = new CustomFinalizer(referent, referenceQueue); | |
referent = null; // making it GC-ready | |
System.gc(); | |
// you probably need a separate thread for real application | |
var aRef = referenceQueue.remove(); // XXX it's blocking | |
((CustomFinalizer)aRef).finalizeResources(); | |
aRef.clear(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment