简体   繁体   English

在Java中使用finalize()是否合适?

[英]Is it ever appropriate to use finalize() in Java?

I've got an Android project that heavily uses C++ JNI shared objects. 我有一个Android项目,该项目大量使用C ++ JNI共享对象。 In fact, I've got a Java object that manages resources allocated from JNI calls. 实际上,我有一个Java对象来管理从JNI调用分配的资源。 On that particular Java object, I'm using a finalize() call to handle the freeing of those native resources when the object gets destroyed. 在那个特定的Java对象上,我正在使用finalize()调用来处理对象被销毁时释放的本机资源。

This all seems to work and I don't see any memory leaks, however, I've heard that you using Java finalizers is frowned upon (Effective java, 2nd edition page 27. Item 7: Avoid finalizers, etc.). 这一切似乎都有效,并且我看不到任何内存泄漏,但是,我听说您不赞成使用Java终结器(有效Java,第2版,第27页。项目7:避免终结器等)。 Are there cases, such as the one I've described above, where using finalize() is appropriate? 是否存在某些情况(如上文所述)适合使用finalize()? I'm not sure what else to do to ensure that those native resources get cleaned up. 我不确定要采取哪些其他措施来确保清理这些本机资源。

我相信您的案例是少数适合使用finalizer的案例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM