2

I am making a Windows JNI .dll. I am trying to determine whether the JVM can ever make concurrent calls to the same native function. Here is the Java code I wrote:

public class TestThreads implements Runnable
{
    public void run()
    {
        MyJNIClass.f(); // Call 'native' static member function
    }
    public static void main(String[] args)
    {
        for (int k = 0; k < 20; ++k)
            new Thread(new TestThreads()).run();
    }
}

On the native side, the function MyJNIClass.f() is implemented like so:

#include <jni.h>
#include <windows.h>
#include <iostream>

extern "C"
{
    JNIEXPORT void JNICALL Java_MyJNIClass_f(JNIEnv * env, jclass clazz)
    {
        std::cout << GetCurrentThreadId() << ", " << GetCurrentThread() << std::endl;
        Sleep(500);
    }
}

The output from the native function indicates that all the calls are running from the same Win32 thread:

5196, 0xfffffffe
5196, 0xfffffffe
5196, 0xfffffffe
5196, 0xfffffffe
5196, 0xfffffffe
5196, 0xfffffffe
5196, 0xfffffffe
5196, 0xfffffffe
5196, 0xfffffffe
...

...and each of these lines pops out about half a second after the previous one.

So is the only way to get the native side to use multiple threads like the JVM to create a worker thread on the native/DLL side and then return immediately!?!?

4

2 回答 2

4

You have only one thread which is "main" which was created for you.

I suspect you intended to call start(); which calls run(); in a new thread, instead of reusing the current thread.

于 2013-06-20T00:01:48.120 回答
0

I would also add, JNI isn't serialized, you can call from multiple threads.

于 2013-06-20T05:42:31.483 回答