Aristarhys
Aristarhys

Reputation: 2122

JNI cleanup and daemon threads in Android NDK

So thats the flow of JNI

JNI_onLoad - get JavaVM (get jclass for calling static methods)

Then need to call something from Java to C:

GetEnv() to get JNIEnv and AttachCurrentThread() to use it.
Call java method
Process java method returned value.
DetachCurrentThread() - free thread
Somethere in the end
DestroyJavaVM()

Well questions are:

  1. There to call DestroyJavaVM() and if i need to do so? In onDestroy() in my main Activity?
  2. Is JNI_onUnload ever call and what i must clean up there?
  3. Do i need somehow free jclass which i stored in static global vaiable?
  4. Do JNI free local out of scope jarrays/jarrays elements, strings and string chars, jobjects after function return or i must always keep eye on that (calling env->Release(something))
  5. What is benefits and usage of AttachCurrentThreadAsDaemon()?

Upvotes: 2

Views: 3671

Answers (1)

Gil
Gil

Reputation: 3334

  1. DestroyJavaVM() must be called when you no longer use the JVM (probably at the end of your program).

  2. JNI_onUnload is called when the class is unloaded (because its class loader was deleted for example).

  3. to free a Class null its references and delete its classloader.

  4. JNI jarrays/jarrays elements, strings and jobjects are either allocated by the JVM or using a C buffer (that you manage); see #3 for the former case.

  5. AttachCurrentThreadAsDaemon() tells the JVM that it should not wait for the thread to exit upon shutdown (helpful for daemons).

Good luck!

Upvotes: 3

Related Questions