Will JVM threads always maintain their mapping to OS threads

Kellen :

I'm writing a service that uses JNA to delegate work from Java to a native C++ library. The C++ library makes an async call for a computationally expensive task, and then gets a callback (on a different OS thread) when that task is complete. I would like to route the result of this work back to the correct thread in JVM.

What I'm wondering is can I be guaranteed that the JVM thread id will always have a one to one mapping with a native thread_id? I.e. if I record the thread id in C++ via

std::this_thread::get_id()

then kick off some expensive work and block on a cv, that the thread will still be there once the work is complete, and that I'll be able to return results to JVM correctly. Will any behind-the-scenes JVM work like JIT, GC, or stop the world collections be causes for concern with this pattern?

Stephen C :

The answer is not specified in the JLS, the JVM spec or the Javadocs.

Indeed, it is possibly platform specific. For example, in JVMs for Solaris it is (or was) possible to do N:M mapping of user-space threads to kernel-space threads; see this document. It is not clear what that means / meant for the native thread id.

So will a thread's native thread_id be constant for the JVM that you are using?

There is only one way to be sure: download the JVM source code and check.

Warning: it is fearsome complicated!

(And you should probably take that as a hint that you shouldn't be doing this kind of thing ... if you have to resort to asking on StackOverflow if it will work!)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=121701&siteId=1