0

I've found here https://stackoverflow.com/a/12901159/6655884 a function call where it attaches the thread with AttachCurrentThread, does the call and then detaches it with DetachCurrentThread.

I want to know if this process is costly. I have a C++ function

void sendEvent(Event event) {
    //call java function here
}

that will be called by several C++ threads to send events to the Java side, so I cannot simply attach a thread and never detach it because many different threads are going to call sendEvent. So I wanna know if doing AttachCurrentThread, calling Java and then DetachCurrentThread at every sendEvent call is costly. If it is, what should I do instead?

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • 1
    You can set up a thread destructor callback to detach the thread from the JVM when the thread is destroyed. See the final part of https://stackoverflow.com/questions/30026030/what-is-the-best-way-to-save-jnienv/30026231#30026231 Note that with recent NDK versions you can accomplish the same thing with even less code using `thread_local`s. – Michael Nov 12 '19 at 09:41
  • 1
    Attaching and detaching threads are costly operations, which could cost you tens of milliseconds in bad conditions. In your situation, it'd be better to use some kind of pool of pre-attached threads or one attached thread with task queue – Daniil Vlasenko Nov 12 '19 at 12:27

1 Answers1

4

Although you CAN attach the calling thread on a per-JNI-call basic, you really SHOULD NOT, unless you have no other choice. A native thread MUST attach itself to the JVM before it can make JNI calls. To avoid unnecessary overhead, the thread really should attach itself as soon as possible (at least before the 1st JNI call), and stay attached until it no longer needs to make any further JNI calls.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770