Why would you ever implement finalize()?

前端 未结 21 2638
耶瑟儿~
耶瑟儿~ 2020-11-22 16:50

I\'ve been reading through a lot of the rookie Java questions on finalize() and find it kind of bewildering that no one has really made it plain that finalize()

21条回答
  •  醉梦人生
    2020-11-22 17:23

    Be careful about what you do in a finalize(). Especially if you are using it for things like calling close() to ensure that resources are cleaned up. We ran into several situations where we had JNI libraries linked in to the running java code, and in any circumstances where we used finalize() to invoke JNI methods, we would get very bad java heap corruption. The corruption was not caused by the underlying JNI code itself, all of the memory traces were fine in the native libraries. It was just the fact that we were calling JNI methods from the finalize() at all.

    This was with a JDK 1.5 which is still in widespread use.

    We wouldn't find out that something went wrong until much later, but in the end the culprit was always the finalize() method making use of JNI calls.

提交回复
热议问题