0

Jni has methods GetArrayElements and GetPrimitiveArrayCritical.

I know the *critical methods add gc lock to prevent gc when jni code is executing in critical sections, but if jni code is executing non-critical methods and gc happens, the array elements may be moved by gc. In this situation, native code may hold a wrong address. I don't know how jvm handle this, or if i misunderstand something.

Yang Song
  • 11
  • 4
  • 1
    The short answer is that it doesn't handle it. If your native code tries to access array elements without holding the GC lock then it is broken, and you risk causing a JVM crash. Does the JVM try to prevent your native code doing this? Nope! Could it prevent it? Nope! – Stephen C Aug 04 '22 at 05:23
  • I think you misunderstand what GetArrayElements is allowed to do: in the best case it *pins* that array to memory, ensuring that it is not moved until the pointer is released, or it makes a copy and then the JVM is free to move the backing array around. Of course it must then copy everything back when you call Release. – Botje Aug 04 '22 at 07:10

0 Answers0