tags:

views:

134

answers:

1

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 applies specifically to Sun JDK 6 on Windows XP.

+1  A: 

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.

kdgregory
Darn, I was looking at the JDK5 JNI spec all the time. The "Detaching from the VM" section is new in the JDK6 docs. Thanks for your help!
Ronald Blaschke