THIS SHOULD BE OBSOLETE WITH JAVA 9!
Use java.util.Cleaner
instead! (Or sun.misc.Cleaner
on older JRE)
Original post:
I found that the use of PhantomReferences has nearly the same amount of pitfalls as finalizer methods (but a fewer problems once you get it right).
I have written a small solution (a very small framework to use PhantomReferences) for Java 8.
It allows to use lambda expressions as callbacks to be run after the object has been removed. You can register the callbacks for inner resources that should be closed.
With this I have found a solution that works for me as it makes it much more practical.
https://github.com/claudemartin/java-cleanup
Here's a small example to show how a callback is registered:
class Foo implements Cleanup {
//...
public Foo() {
//...
this.registerCleanup((value) -> {
try {
// 'value' is 'this.resource'
value.close();
} catch (Exception e) {
logger.warning("closing resource failed", e);
}
}, this.resource);
}
And then there is the even simpler method for auto-close, doing about the same as the above:
this.registerAutoClose(this.resource);
To answer your questions:
[ then whats the use of it ]
You can't clean up something that doesn't exist. But it could have had resources that still exist and need to be cleaned up so they can be removed.
But what is the use of this concept/class?
It's not necessarily to do anything with any effect other than debugging/logging. Or maybe for statistics.
I see it more like a notification service from the GC.
You could also want to use it to remove aggregated data that becomes irrelevant once the object is removed (but there are probably better solutions for that).
Examples often mention database connections to be closed, but I don't see how this is such a good idea as you couldn't work with transactions. An application framework will provide a much better solution for that.
Have you ever used this in any of your project, or do you have any example where we should use this? Or is this concept made just for interview point of view ;)
I use it mostly just for logging. So I can trace the removed elements and see how GC works and can be tweaked. I wouldn't run any critical code in this way. If something needs to be closed then it should be done in a try-with-resource-statement.
And I use it in unit tests, to make sure I don't have any memory leaks. The same way as jontejj does it. But my solution is a bit more general.
FakeReference
orNonReference
. – Bracketing