JNI calling Java from C ++ with multiple threads

I am working on a project where I call Java functions from C ++ code (using JNI) and I have a multithreading problem. I want to call the Java search function, and for each call I want to create a separate thread. I have a singleton MainClass and a nested Query class. The Query class inherits from QThread . The code is as follows

 MainClass::MyQuery query("<some search query>"); query.LaunchQuery(); //functions of Query void MainClass::MyQuery::LaunchQuery() const { this->start(); } void MainClass::Query::run() { const MainClass& mainClass = MainClass::GetInstance(); const jclass& obj = mainClass.GetClass(); JNIEnv& env = mainClass.GetJavaEnvironment(); jmethodID methodId = env.GetMethodID(obj, "SearchQuery", "(Ljava/lang/String;)V"); //Run-time error if(methodId != 0) { //calling "SearchQuery" function } 

Now, if you run this code in one thread - everything is fine, but if you try to execute on the code - using multithreading, it causes a runtime error by the message "Unhandled exception at 0x777715de in MyApp.exe: 0xC0000005: Access violation reading location 0x000000ac." when I try to get the method id. I tried also with boost::thread , but the result was the same.

So why does this fail when I do it in a separate thread, when everything is fine in one thread? Any ideas?

+7
c ++ multithreading qt jni runtime-error
source share
1 answer

Scroll down to "Join Virtual Machine" in JNI docs:

http://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/invocation.html

The JNI interface pointer (JNIEnv) is only valid in the current thread. If another thread needs to access the Java virtual machine, it must first call AttachCurrentThread () to attach itself to the virtual machine and get the JNI interface pointer.

+8
source share

All Articles