JNI(Java Native Interface)在多线程中的运用

引文地址: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文档上有明确表述

  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中调用:

    

 

 在另一个线程B,调用

 

 

 

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

 

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


示例代码如下:

(1)java代码:Test.java:

 

 

 

(2) DLL代码:Test.cpp:


 

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.

posted @ 2008-08-19 09:10  lovingprince  阅读(6552)  评论(0编辑  收藏  举报