How to use JNI in a multithreaded environment_ CreateJavaVm(C)
I am working in JNI using C as my mother tongue I can create (c) shared libraries, and I can call Java functions with the help of shared libraries
Steps involved in my process:
1) Using JNI_ Createjavavm create VM [IN C]
2) Use the VM created for processing
3) Exit thread
If I will perform the same process again, JNI_ Createjavavm does not create any VMS, and it returns the JNI error code as - 1 (unknown error) Then I check that getcreatedjavavms returns 0, and I try to get env getenv. It crashes
I also tried the getjavavm function, but it is crashing with an error message,
# # A Fatal error has been detected by the Java Runtime Environment: # # SIGSEGV (0xb) at pc=0x00c1b3ed,pid=8645,tid=2961177456 # # JRE version: 7.0_25-b15 # Java VM: Java HotSpot(TM) Server VM (23.25-b01 mixed mode linux-x86 ) # Problematic frame: # C [libVsphere.so+0x6a3ed] _Jv_jnienv::GetJavaVM(_Jv_JavaVM**)+0xb
Why and how to solve this problem?
How to use JNI in a multithreaded environment_ CreateJavaVm,JNI_ Getcreatedvms and getjavavm
Solution
You should only create a JavaVM global instance at the beginning of the program in a thread:
/* Global instance */ JavaVM *jvm; int main() { /* ...call to JNI_CreateJavaVm ...*/ }
Then, on each thread, if you want to get the Java environment, you should use the global pointer (JVM) to the Java machine:
jnienv *env; (*jvm)->AttachCurrentThread(jvm,(void **)&env,NULL);
Finall can access methods / classes, etc. using this environment:
jclass ex = (*env)->FindClass(env,"java/lang/NullPointerException");