Do I Have to JNI Detach an Attached Thread?
I have some native thread that needs to call into Java. For that, I need to attach the thread to the VM using AttachCurrentThread
. Since this callback will happen quite often, the thread should probably stay attached. Calling AttachCurrentThread
multiple times is fine ("Trying to attach a thread that is already attached is a no-op.")
Do I have to call DetachCurrentThread
before the thread exits, will it happen automatically, or is it not even required? What happens if I must call detach, but don't? Would it just "leak," or could this even corrupt the VM state?
I have checked the Java Native Interface specification, but either missed this, or it really is unspecified.
My question a开发者_JAVA百科pplies specifically to Sun JDK 6 on Windows XP.
I think that the confirmation that you want is here: http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/invocation.html#wp1060
A native thread attached to the VM must call DetachCurrentThread() to detach itself before exiting.
And in the next section, there's the rationale:
The VM waits until the current thread is the only non-daemon user thread before it actually unloads. User threads include both Java threads and attached native threads.
精彩评论