They both can be used for cleanup, there is almost no guarantees, but PR requires more harness coding. So, having two options, why exactly I have to prefer one to another?
Javadoc 9 describes finalize as very problematic, but that doesn't make its alternative better automatically, right?
Also javadoc describes PhantomReference
as providing "more flexible and efficient ways to release resources when an object becomes unreachable", but without a reason specified. Well, I guess these guys know some secrets, but I'm wondering - can't be this choice made more obvious?
The difference
Here are all the differences between finalize (FZ) and pantom reference (PR) I discovered, please correct me if I missed something.
Can be used for cleanup actions?
- Yes for both.
Requires a new thread to maintain?
- PR: yes, you must define a queue watcher thread in order to do cleanup ASAP
- FZ: no
Requires a new class to define?
- PR: yes, you must extend
PhantomReference
to act meaningfully - FZ: no
- PR: yes, you must extend
Can cleanup processor access the referent object?
- PR: no
- FZ: yes, and that's handy
Does it work reliably in my personal practice?
- Yes for both.
Can lead to performance issues, deadlocks, and hangs?
- Yes for both. Depends on your code, isn't?
Can errors in a cleanup processor lead to resource leaks?
- Yes for both. Depends on your code, isn't?
Cancelable if it is no longer necessary?
- PR: yes
- FZ: no, if speaking strictly, but is immediate
return
that bad?
Is invocation ordering between multiple instances specified?
- PR: no info
- FZ: no - "no ordering is specified among calls to finalize methods of different objects" (java.lang.Object)
Invocation guaranteed?
- PR: no info - you can only "request to be notified of changes in an object's reachability" (java.lang.ref)
- FZ: no - "The finalize method might be called on a finalizable object only after an indefinite delay, if at all" (java.lang.Object)
Any guarantees regarding the timing?
- PR: no - "Some time after the garbage collector determines that the reachability of the referent has changed to the value corresponding to the type of the reference" (java.lang.ref)
- FZ: no - "The Java programming language does not specify how soon a finalizer will be invoked" (JLS), "The finalize method might be called on a finalizable object only after an indefinite delay, if at all" (java.lang.Object)
Can
this
resurrect during processing?- PR: no, and that's not bad
- FZ: yes, officially supported