Skip to content
Advertisement

JNI 8 C++ : Thread attach and detach And async callback

How to async call Java method from std::thread ?

Let’s assuming this is a IM bot sdk, Because it’s logic basicly a IM bot sdk.

The most importtant is: How to async call java method and callback native.

There is logic flow at the bottom, Maybe helpful.

For example:

Receive message A “backup”, Then call the java plugin with MsgA, The plugin porcess this event need 10second, And call 5 time native method for what ever it need.

Mean while, Receive message B “echo”, That only take 10ms to process, And send an message by invoke native method.

So, MsgB recived after MsgA, But finish befor MsgA.

If using pure C C++ java or what ever, That will be so easy to achive. But here I found a headache problem: JNI thread Attach.

※ First question: Wired JNI attach

I have read doc find answer, None of them working and my condition different with everyone

I’m using Zulu JDK8 (zulu8.48.0.53-ca-fx-jdk8.0.265-win_x64) and MinGW64 C++, For demo:

JavaScript

Here is the worker function in C++

JavaScript

And without attach we will get, That is expected:

JavaScript

And add the tWorker function for t1:

JavaScript

I got this:

JavaScript

Some answer say you should use GetEnv:

JavaScript

Got same result:

JavaScript

For more post I found, Replace Local to Global (That dosen’t make any sense for logic and Document but in their question problem solved)

JavaScript

That is usless, Even I try all 16 combination, That not work for me.

JavaScript

Question one: What happen in there?

※ Second Question: How to achive that:

Logic flow for what I'm doing

Update 1:

Question 1 solved.

JavaScript

Without cast will cause a complie error error: invalid conversion from 'JNIEnv**' {aka 'JNIEnv_**'} to 'void**' [-fpermissive]

Advertisement

Answer

Looks like the your problems are not in usage of JVM but in C++ code. Looking at this piece of code:

JavaScript

Pay attention here:

JavaScript

Your args is a pointer and is not initialized. It invokes undefined behavior, is most likely to crash.
Also you are trying to delete it uninitialized:

JavaScript

Also I don’t understand this piece of code:

JavaScript

What is the sense of reinterpret_cast here? By definition of the function there is required a pointer to pointer, not a cast:

JavaScript

Ok, you can cast it, but you should pass pointer to pointer here, so cast a pointer to pointer static_cast<void**>(&lEnv), but it is probably not required.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement