简体   繁体   中英

How to use JNI_CreateJavaVm in a multi threaded environment (C++)

I'm Working in JNI with C++ as my native .I'm able to create the (c++) shared library and i'm able to call the java functions with the help of shared library.

Steps involved in my process:

1) Creating VM by using JNI_CreateJavaVm.[IN C++]

2) Process with the created VM.

3) Exit from the Thread

If i will again doing the same process the JNI_CreateJavaVm is not creating any VM and it is returning the JNI error code as -1 (Unknown error).Then I check for the getCreatedJavaVMs returns which returns 0, while I try to get the env with GetEnv it crashed.

I also tried the function GetJavaVM but it is getting crashed with the 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 it is happening and how to solve the issue?

How to use the JNI_CreateJavaVm,JNI_GetCreatedVMs and GetJavaVM in a multithreaded environment.

You should have only one global instance of the JavaVM created at the begin of the program in one thread only :

/* Global instance */
JavaVM *jvm;

int main() {
/* ...call to JNI_CreateJavaVm ...*/
}

Then on each thread if you want to grab the Java environment, you should do it using the global pointer to the java machine ( jvm ):

JNIEnv *env;
(*jvm)->AttachCurrentThread(jvm, (void **)&env, NULL);

Finall using that environment you can access methods / classes, etc :

jclass ex = (*env)->FindClass(env, "java/lang/NullPointerException");

You can use AttachCurrentThread() to attach the current thread to the existing Java VM. There is no need to create JavaVM for every thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM