THIS SHOULD BE BETTER WITH JAVA 9!
Use java.util.Cleaner instead! (Or sun.misc.Cleaner on the older JRE)
Original post:
I found that using PhantomReferences has almost the same number of pitfalls as the finalizer methods (but with less problems when you get it right). I wrote a small solution (a very small basis for using PhantomReferences) for Java 8. It allows you to use lambda expressions as callbacks that will be executed after the object is deleted. You can register callbacks for internal resources that need to be closed. With this, I found a solution that works for me, as it makes it much more practical.
https://github.com/claudemartin/java-cleanup
Here is a small example showing how the callback is registered:
class Foo implements Cleanup {
And then there is an even simpler method of automatic closing, doing roughly the same thing as above:
this.registerAutoClose(this.resource);
To answer your questions:
[what uses it]
You cannot purify that which does not exist. But he might have resources that still exist, and they need to be cleaned up so that they can be removed.
But what is the use of this concept / class?
It is not necessary to do anything with any effect other than debugging / logging. Or maybe for statistics. I see that this is more like a notification service from the GC. You can also use it to remove aggregated data that becomes irrelevant after deleting an object (but there are probably better solutions for this). The examples often mention database connections that you need to close, but I donโt see how such a good idea, how you could not work with transactions. The application framework will provide a much better solution for this.
Have you ever used this in any of your projects, or do you have any example where we should use it? Or this concept is made only for the interview point of view;)
I use it mainly for logging only. Therefore, I can track deleted items and see how the GC works and can be changed. Thus, I will not run critical code. If something needs to be closed, this should be done in a try-with-resource-statement. And I use it in unit tests to make sure that I have no memory leaks. Just like jontejj. But my solution is a little more general.
May Day May 29 '14 at 9:30 a.m. 2014-05-29 09:30
source share