Why is the finalize() method in java.lang.Object “protected”?

前端 未结 9 1271
旧时难觅i
旧时难觅i 2020-11-29 04:28

Out of curiosity,

Why is the finalize() method\'s access modifier is made as protected. Why cant it be public? Can someone exp

9条回答
  •  情深已故
    2020-11-29 05:01

    • finalize is meant to be called by the gc only and as such does not require public access
    • finalize is guaranteed to be called only once by the gc, calling it yourself will break this guarantee, as the gc wont know about it.
    • Any overriding class can make finalize public, which I believe is bad for the above reasons
    • finalize should not contain much code, as any exception thrown by finalize may kill the finalizer thread of the gc.

    Rant against finalize()

    • Managing native resources or any resource which requires dispose() or close() to be called may cause hard to find bugs as they will only be released when the jvm runs out of memory, you should release resources manually. Finalize should only be used for debugging resource leaks or for cases where managing resources manually is too much work.
    • finalize will be called in an additional thread of the gc and may cause problems with resource locking and so on.
    • the reference classes like WeakReference and ReferenceQueue are an alternative (rather complex) way to deal with cleanup and may have the same problems as finalize() for native resources.

    Beware of errors in the above statements, I'm a bit tired :-)

提交回复
热议问题