Why shouldn't I use finalize?

Asked 2 years ago, Updated 2 years ago, 30 views

I was told that we should not implement the finalize cleanup process of Java, but why is that so?
Also, is it possible to do something similar without using finalize?

java

2022-09-30 18:41

2 Answers

It was written very well in the comments, so I will summarize it myself.

You don't know when finalize will be called, or you may not be called.Because it also depends on the implementation of the JVM, the portability of the code is lost.Also, the finalize is executed on the finalize thread, but an exception here does not result in an error, and the object may remain in the memory in a half-finished state.
Therefore, you should not write about any process that relies on such unstable processing.


2022-09-30 18:41

There are various blogs and articles, but the most detailed one is this page of JPCert.

https://www.jpcert.or.jp/java-rules/met12-j.html

What I'm particularly concerned about is

  • You do not know how long the finalizer will be delayed after the object becomes unreachable.
  • JVM may terminate without performing a finalizer for unreachable objects.In other words, any attempt to update an important persistent state (of an object) in the finalizer method may fail without warning.→ In other words, the file lock or connection pool may remain.

…and many other shortcomings, strongly stating that it should not be implemented independently.

I can't say it's an alternative to finalyze, but do you want to open up the resources you've acquired (don't leave them alone, don't forget to handle exceptions)?


2022-09-30 18:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.