Skip to content Skip to sidebar Skip to footer

Right Way To Work With Jni In Multithreading Application

Description In my C++ application class JNIXMLDocument which made some JAVA method calls. In the constructor of JNIXMLDocument class I attach current thread and set it to my class

Solution 1:

Is it right to set JNI interface pointer (JNIEnv* m_JavaEnv) in the constructor once and use it in the whole code ?

No. It is thread-specific. That's what Attach/DetachCurrentThread are for. The only way this can work is if the C++ object is constructed and destroyed in the same thread.

Is it right to set jclass m_XMLDocumentClass in the constructor and than use that variable in the all methods ?

No. It is a local reference, and it expires when the JNI method it was acquired in returns. You must save as a global or weak reference unless it is only going to be used within a single JNI method.

Is it right to set jobject m_XMLDocumentObject in the constructorinthis way m_JavaEnv->NewObject(m_XMLDocumentClass , constructor);

No: see above.

or maybe I must call NewGlobalRef.

Yes, as above.

What problems can appear if my application work not in the same thread (use many threads) ?

Mainly JVM crashes. The JVM assumes you follow all the rules in the JNI specification. So do that.

Post a Comment for "Right Way To Work With Jni In Multithreading Application"