Multithreading / JNIEnv in the wrong thread / JDK 1.6
I've written a multihreaded application using JNI as interface for communicating with a kind of data storage ( C-app).
I've learned from the doc that the JNIEnv-Pointer stores thread specific data and therefore only the thread which instantiated the JNI-interface is allowed to use native calls. All other threads terminate the app with a "JNIEnv in the wrong thread
" error message.
According to JNI-doc I've found some lines describing this problem and they give a solution by using the JNI-APIAttachCurrentThread. However I do not really understand who to use this API. Does this mean that I've to instantiate the threads from the C-scope (analogous callbacks)?
A rough sketch of my "situation":
MainThread -(init) - JNI-InterfaceClass()
|create ThreadApp1()
|create ThreadApp2()
|.....
ThanX
/franzR
[884 byte] By [
fr_java_3a] at [2007-11-26 14:46:00]

# 1
Hi,
in my JNI SDK for C++ and .NET (1.1 and 2.0) I have solved this problem. My code traces threads (native and Java) and attaches threads to JVM. The variable of type JNIEnv is hiddes from Developer, he only calls proper JNI functions without this parameter. See my tools
- for C++ in MS VS6.0
http://www.simtel.net/product.php[id]93174[sekid]0[SiteID]simtel.net
- for C++ in MS VS7.1
http://www.simtel.net/product.php[id]94368[sekid]0[SiteID]simtel.net
- for C++, MCpp, C#, J#, VB (.NET1.1)
http://www.simtel.net/product.php[id]98493[sekid]0[SiteID]simtel.net
http://www.simtel.net/product.php[id]95126[sekid]0[SiteID]simtel.net
- for MCpp, C#, J#, VB (.NET 2.0)
http://www.simtel.net/product.php[id]98653[sekid]0[SiteID]simtel.net
The last update of these products supports SUN/IBM JDK1.1x-1.6.x, MS Java 1.1.4, i.e. you can write native code that runs with any JVM without modifications.
# 2
In your native code you can call AttachCurrentThread to attach the current thread to a JNI context. if you already have one it will return the current one, otherwise it will create a new one. If you're already attached it a fairly cheap call. So the idea is that before you use JNI you call AttachCurrentThread to get your context.
tom