Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jni starter question


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.

like image 646
Cratylus Avatar asked Oct 11 '22 16:10

Cratylus


2 Answers

Yes, the JVM will just terminate which is one of the reasons why JNI code is really hard to debug. If you are using C++ code you can use exceptions and then map them to a Java exception which at least gives you some level of security but doesn't help with things like bad memory access etc.

From an architecture point of view I suggest to decouple you code from JNI as much as possible. Create a class / procedure structure that is entirely testable from C++/ C and let the JNI code do only all the conversion stuff. If the JVM then crashes you at least know where you have to look.

like image 123
Daff Avatar answered Oct 14 '22 23:10

Daff


The principles are no different from any multi-threaded C application:

  1. Always check all your input thoroughly.
  2. Always free up temporary memory you allocated.
  3. Make sure your functions are re-entrant.
  4. Don't rely on undefined behaviour.

The Java virtual machine offers you no extra protection for your native code, if it fails or is leaking, your VM will fail or leak.

like image 32
biziclop Avatar answered Oct 15 '22 00:10

biziclop