Will JVM threads always maintain their mapping to OS threads

Viewed 242

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?

2 Answers

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

It seems like a bad design to me, that requires you to know how the JVM works.

If you anyway marshal some Java data to the C++ layer, why not marshal a callback + context? when the C++ thread finishes processing the data, it calls the Java callback with the provided context and in the Java layer - you push the result back to the Java thread.

the C++ layer shouldn't know anything about how Java threads work - all it has to do is to call a callback and let the callback deal with the implementation details.

I've actually done this a few times in the past but in C# and P/Invoke, which easily allows you to marshal a C# function as a C-function pointer. I'm sure it's possible for JNI as well.

Related