Home:ALL Converter>Are JNI native invocations from different Java threads sequentialized?

Are JNI native invocations from different Java threads sequentialized?

Ask Time:2013-06-20T07:56:47         Author:0xbe5077ed

Json Formatter

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!?!?

Author:0xbe5077ed,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/17203260/are-jni-native-invocations-from-different-java-threads-sequentialized
Peter Lawrey :

You have only one thread which is \"main\" which was created for you.\n\nI suspect you intended to call start(); which calls run(); in a new thread, instead of reusing the current thread.",
2013-06-20T00:01:48
yy