JNI thread model?

后端 未结 1 927
半阙折子戏
半阙折子戏 2021-02-14 14:54

When I call a C/C++ from Java, is a new thread created by JavaVM or JNI to run the C/C++ code while my Java thread is waiting? I ask this because my C/C++ code runs something on

相关标签:
1条回答
  • 2021-02-14 15:42

    The JNI does not create any new thread behind the scene. A native function is executed in the same thread as the java method that calls the native function. And vice versa when native code calls a java method then the the java method is executed in the same thread as the native code calling the method.

    It has consequence - a native function call returns to java code when the native function returns and native code continues execution when a called java method returns.

    When a native code does a processing that should run in a separate thread the the thread must be explicitly created. You can either create a new java thread and call a native method from this dedicated thread. Or you can create a new native thread in the native code, start it and return from the native function.

    // Call a native function in a dedicated java thread
    native void cFunction();
    ...
    new Thread() {
        public void run() {
            cFunction();
        }
    };
    

    // Create a native thread - java part
    native void cFunction()
    ...
    cFunction();
    
    //  Create a native thread - C part
    void *processing_function(void *p);
    JNIEXPORT void JNICALL Java____cFunction(JNIEnv *e, jobject obj) {
        pthread_t t;
        pthread_create(&t, NULL, processing_function, NULL);    
    }
    

    If you use the second variant and you want to call a java callback from a thread created natively you have to attach the thread to JVM. How to do it? See the JNI Attach/Detach thread memory management ...

    0 讨论(0)
提交回复
热议问题