chap 18:JNI在多线程中的应用

32 篇文章 0 订阅
6 篇文章 0 订阅

引文地址:http://blog.csdn.net/hust_liuX/archive/2006/12/25/1460486.aspx

我在这里将文章整理了一下,重新修改了部分描述和增加了一些重要的说明事项。修改文如下:

问题描述:

一个java对象通过JNI调用DLL中一个send()函数向服务器发送消息,不等服务器消息到来就立即返回,同时把JNI接口的指针JNIEnv *env(虚拟机环境指针),jobject obj保存在DLL中的变量里.

一段时间后,DLL中的消息接收线程接收到服务器发来的消息,
并试图通过保存过的envobj来调用先前的java对象的方法(相当于JAVA回调方法)来处理此消息.此时程序会突然退出(崩溃).

解决办法:

    解决此问题首先要明白造成这个问题的原因。那么崩溃的原因是什么呢?

 

JNI文档上有明确表述:  TheJNIEnv pointer, passed as the first argument to every nativemethod, can only be used in the thread with which it is associated. It is wrongto cache theJNIEnv interface pointer obtained from one thread, and use thatpointer 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;

env->GetJavaVM(&gs_jvm); //来获取JavaVM指针.获取了这个指针后,将该JavaVM保存起来。

 

在另一个线程B,调用

JNIEnv *env;

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

 

//这里就获得了B这个线程在jvm中的JNIEnv指针.

 

这里还必须获取那个java对象的jobject指针,因为我们要回调JAVA方法. JNIEnv 指针一样,jobject指针也不能在多个线程中共享.就是说,不能直接在保存一个线程中的jobject指针到全局变量中,然后在另外一个线程中使用它.幸运的是,可以用   

1.     gs_object=env->NewGlobalRef(obj);//创建一个全局变量

来将传入的obj(局部变量)保存到gs_object,从而其他线程可以使用这个gs_object(全局变量)来操纵这个java对象了.


示例代码如下:

(1)java代码:Test.java:

1.     import java.io.*;

2.     class Test implementsRunnable

3.     {

4.     public int value  = 0;

5.     static{System.loadLibrary("Test");}

6.      

7.     public native voidsetEnev();//本地方法

8.      

9.     public static voidmain(String args[]) throws Exception

10. {

11.     Test t= new Test();

12.    t.setEnev(); //调用本地方法

13.  

14.     while(true)

15.     {

16.       Thread.sleep(1000);

17.       System.out.println(t.value);

18.     }

19.    }

20. }

21.  

22.  

(2) DLL代码:Test.cpp:

 

1.    #include "test.h"

2.    #include<windows.h>

3.    #include<stdio.h>

4.    static JavaVM *gs_jvm=NULL;

5.    static jobject gs_object=NULL;

6.    static int gs_i=10;

7.     

8.    JNIEXPORT void JNICALL Java_Test_setEnev(JNIEnv *env,jobject obj)

9.    {

10.        env->GetJavaVM(&gs_jvm);//保存到全局变量中JVM

11.       //直接赋值objDLL中的全局变量是不行的,应该调用以下函数:

12.       gs_object=env->NewGlobalRef(obj);

13.    

14.   HANDLE ht=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadFun,0,NULL,NULL);

15.   }

16.    

17.   void WINAPI ThreadFun(PVOID argv)//JNI中线程回调这个方法

18.   {

19.   JNIEnv *env;

20.   gs_jvm->AttachCurrentThread((void **)&env, NULL);

21.   jclass cls = env->GetObjectClass(gs_object);

22.   jfieldID fieldPtr =env->GetFieldID(cls,"value","I");

23.    

24.   while(1)

25.   {

26.        Sleep(100);

27.      //这里改变JAVA对象的属性值(回调JAVA

28.      env->SetIntField(gs_object,fieldPtr,(jint)gs_i++);

29.      }

30.   }

31.    

32.    

JNI

There are certain constraints that you mustkeep in mind when writing native methods that are to run in a multithreadedenvironment. By understanding and programming within these constraints, yournative methods will execute safely no matter how many threads simultaneouslyexecute a given native method. For example:

·  A JNIEnv pointer is only valid in thethread associated with it. You must not pass this pointer from one thread toanother, or cache and use it in multiple threads. The Java virtual machinepasses a native method the same JNIEnv pointer in consecutive invocations fromthe same thread, but passes different JNIEnv pointers when invoking that nativemethod from different threads. Avoid the common mistake of caching the JNIEnvpointer of one thread and using the pointer in another thread.

·  Local references are valid only in thethread that created them. You must not pass local references from one thread toanother. You should always convert local references to global referenceswhenever there is a possibility that multiple threads may use the samereference. 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值