So we have finalize()
that is called when the garbage collector intends to remove the object from memory.
Is there a similar method that gets called once all references have gone missing?
If yes, could one not reference it again? (This I imagine could be the reason why there are no such methods)
Asked
Active
Viewed 41 times
1

GRASBOCK
- 631
- 6
- 16
-
1Are you talking about something similar to [Automatic Reference Counting](https://docs.swift.org/swift-book/LanguageGuide/AutomaticReferenceCounting.html) that Swift and Objective-C does? I don't think Java does that though. – Sweeper Feb 02 '20 at 09:27
-
1Just a general note: `finalize` and everything around it is heavily dangerous. Using it drastically cuts down performance, since it stands in the way of the garbage collector. And the JVM can not even guarantee you that it is executed properly (read its Javadoc). If you do not have a very convincing reason to use it, never ever use it. – Zabuzard Feb 02 '20 at 09:30
-
2You may use `PhantomReference`s, since Java 9. It basically is a reference level below strong, soft and weak references. So after all "normal" usages of something have gone, it is phantom-reachable. You can use that to hook up procedures. But as noted before, any usage that kicks in before "destruction" heavily slows down the destruction procedure. Quick google example: [Java PhantomReferences: A better choice than finalize()](http://unitstep.net/blog/2018/03/10/java-phantomreferences-a-better-choice-than-finalize/) – Zabuzard Feb 02 '20 at 09:33
-
You can utilize `PhantomReference`s easily using the `Cleaner` API (see [Javadoc](https://docs.oracle.com/javase/9/docs/api/java/lang/ref/Cleaner.html)) introduced with Java 9. It was made as some kind of better replacement for `finalize`. Again, using it will still drastically cut down performance. But it got rid of many of the heavy flaws of `finalize`. – Zabuzard Feb 02 '20 at 09:36
-
There is also a dedicated chapter in **Effective Java** (a very popular Java book) talking in-depth about `finalize` vs `Cleaner` vs alternatives. – Zabuzard Feb 02 '20 at 09:41