引文地址:http://blog.csdn.net/hust_liuX/archive/2006/12/25/1460486.aspx
我在這裡將文章整理了一下,重新修改了部分描述和增加了一些重要的說明事項。修改文如下:
問題描述:
一個java對象通過JNI調用DLL中一個send()函數向伺服器發送訊息,不等伺服器訊息到來就立即返回,同時把JNI介面的指標JNIEnv *env(虛擬機器環境指標),和jobject obj儲存在DLL中的變數裡.
一段時間後,DLL中的訊息接收線程接收到伺服器發來的訊息,
並試圖通過儲存過的env和obj來調用先前的java對象的方法(相當於JAVA回調方法)來處理此訊息.此時程式會突然退出(崩潰).
解決辦法:
解決此問題首先要明白造成這個問題的原因。那麼崩潰的原因是什麼呢?
JNI文檔上有明確表述
The JNIEnv pointer, passed as the first argument to every native method, can only be used in the thread with which it is associated. It is wrong to cache the JNIEnv interface pointer obtained from one thread, and use that pointer in another thread.
意思就是JNIEnv指標不能直接在多線程中共用使用。上面描述的程式崩潰的原因就在這裡:回調時的線程和之前儲存變數的線程共用了這個JNIEnv *env指標和jobject obj變數。
在 http://java.sun.com/docs/books/jni/html/other.html#26206 提到,
JNIEnv *env指標不可為多個線程共用,但是java虛擬機器的JavaVM指標是整個jvm公用的,我們可以通過JavaVM來得到當前線程的JNIEnv指標.
於是,在第一個線程A中調用:
JavaVM* gs_jvm;<br />env->GetJavaVM(&gs_jvm); //來擷取JavaVM指標.擷取了這個指標後,將該JavaVM儲存起來。<br />
在另一個線程B裡,調用
JNIEnv *env;<br />gs_jvm->AttachCurrentThread((void **)&env, NULL);
這裡還必須擷取那個java對象的jobject指標,因為我們要回調JAVA方法.同 JNIEnv 指標一樣,jobject指標也不能在多個線程中共用. 就是說,不能直接在儲存一個線程中的jobject指標到全域變數中,然後在另外一個線程中使用它.幸運的是,可以用
gs_object=env->NewGlobalRef(obj);//建立一個全域變數
來將傳入的obj(局部變數)儲存到gs_object中,從而其他線程可以使用這個gs_object(全域變數)來操縱這個java對象了.
範例程式碼如下:
(1)java代碼:Test.java:
import java.io.*;<br />class Test implements Runnable<br />{<br /> public int value = 0;<br /> static{ System.loadLibrary("Test");}</p><p> public native void setEnev();//本地方法 </p><p>public static void main(String args[]) throws Exception<br /> {<br /> Test t = new Test();<br /> t.setEnev(); //調用本地方法 </p><p> while(true)<br /> {<br /> Thread.sleep(1000);<br /> System.out.println(t.value);<br /> }<br /> }<br />}<br />
(2) DLL代碼:Test.cpp:
#include "test.h"<br />#include<windows.h><br />#include<stdio.h><br />static JavaVM *gs_jvm=NULL;<br />static jobject gs_object=NULL;<br />static int gs_i=10;</p><p>JNIEXPORT void JNICALL Java_Test_setEnev(JNIEnv *env, jobject obj)<br />{<br /> env->GetJavaVM(&gs_jvm); //儲存到全域變數中JVM<br /> //直接賦值obj到DLL中的全域變數是不行的,應該調用以下函數:<br /> gs_object=env->NewGlobalRef(obj);</p><p> HANDLE ht=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFun,0,NULL,NULL);<br />}</p><p>void WINAPI ThreadFun(PVOID argv)//JNI中線程回調這個方法<br />{<br /> JNIEnv *env;<br /> gs_jvm->AttachCurrentThread((void **)&env, NULL);<br /> jclass cls = env->GetObjectClass(gs_object);<br /> jfieldID fieldPtr = env->GetFieldID(cls,"value","I");</p><p> while(1)<br /> {<br /> Sleep(100);<br /> //這裡改變JAVA對象的屬性值(回調JAVA)<br /> env->SetIntField(gs_object,fieldPtr,(jint)gs_i++);<br /> }<br />}<br />
JNI限制:
There are certain constraints that you must keep in mind when writing native methods that are to run in a multithreaded environment. By understanding and programming within these constraints, your native methods will execute safely no matter how many threads simultaneously execute a given native method. For example:
- A JNIEnv pointer is only valid in the thread associated with it. You must not pass this pointer from one thread to another, or cache and use it in multiple threads. The Java virtual machine passes a native method the same JNIEnv pointer in consecutive invocations from the same thread, but passes different JNIEnv pointers when invoking that native method from different threads. Avoid the common mistake of caching the JNIEnv pointer of one thread and using the pointer in another thread.
- Local references are valid only in the thread that created them. You must not pass local references from one thread to another. You should always convert local references to global references whenever there is a possibility that multiple threads may use the same reference.