5


I started looking into JNI and from what I understand is that if a problem occurs with the loaded dll, the jvm is possible to terminate on the spot.
I.e. the process can not be protected e.g. like when catching an exception.
So if my understanding is correct, my question is if there is a standard approach/pattern for this situation when using jni.
Or to state it differently, are processes using jni designed in way to avoid these issues? Or such problems are not expected to occur?

Thank you.

4

3 回答 3

3

是的,JVM 只会终止,这也是 JNI 代码很难调试的原因之一。如果您使用的是 C++ 代码,则可以使用异常,然后将它们映射到 Java 异常,这至少可以为您提供一定程度的安全性,但对诸如错误的内存访问等问题没有帮助。

从架构的角度来看,我建议尽可能将您的代码与 JNI 分离。创建一个完全可从 C++/C 测试的类/过程结构,让 JNI 代码只做所有的转换工作。如果 JVM 然后崩溃,你至少知道你必须看哪里。

于 2011-02-10T20:07:30.490 回答
1

这些原则与任何多线程 C 应用程序没有什么不同:

  1. 始终彻底检查您的所有输入。
  2. 始终释放您分配的临时内存。
  3. 确保您的函数是可重入的。
  4. 不要依赖未定义的行为。

Java 虚拟机不会为您的本机代码提供额外的保护,如果它失败或泄漏,您的虚拟机将失败或泄漏。

于 2011-02-10T20:04:15.437 回答
0

您可以在 JNI 库中拥有与其他任何东西完全相同的错误处理范围。

你可以使用try/catch。如果您在 Windows 上,则可以使用 SEH。如果你在 Linux 上,你可以调用 sigaction。

尽管如此,如果你搞砸了并且有一个 SIGSEGV,那么无论你是否试图捕捉到那个信号,你的 JVM 都可能会干杯。

于 2011-02-11T01:10:48.090 回答