3

When I create a native implementation peer in c++ how can I ensure that native part is also deleted when java object is deleted by JVM? I can add some methods that user of java object has to call explicitly, but I'd like to know if there some hook that I could put to handle when java object is deleted (garbage collected) so that I can automatically delete c++ implementation object as well.

I reviewed JACE it seems that it does that, but I'd need to run PeerEnhancer to patch generated class file (probably that's how it hooks delete? or maybe it needs this patching for something else). However, I'd like to avoid messing with compiled java files, I don't want anything fancy

4

2 回答 2

4

请注意,通过采用终结器,您将在最糟糕的地方逗弄 JVM。在 finalizer() 中调用 JNI 就像在驾驶时调整发动机气门正时。虽然在技术上是可行的,但也很容易导致 JVM 泄漏或崩溃。即使是最轻微的多线程接触,您肯定会在某些时候死锁/崩溃。如果您说“我不想要任何花哨的东西”,我建议您使用显式调用的方法。是的,按照惯例要求某些方法顺序是肮脏的设计,但是 JNI 通常是肮脏的。

如果一个受人尊敬的 JNI 库做了一个隐藏的类检测而不是简单地使用终结器,它可能是有原因的。一些推荐阅读(甚至没有提到 JNI!):

http://asserttrue.blogspot.com/2008/11/finalization-is-evil.html

http://elliottback.com/wp/java-memory-leaks-w-finalize-examples/

我的建议是:是的,使用虚拟方法 detachFromPeer() 实现一个基类,在其中设置一些“分离”标志,然后在终结器中检查带有一些警告的标志。

于 2012-10-24T09:41:58.837 回答
2

在这种情况下,您应该真正使用终结器,但您也应该使您的 Java 类也可关闭。

于 2012-10-24T00:27:13.837 回答