windows 我是否必须 JNI 分离附加线程?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1945813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Do I Have to JNI Detach an Attached Thread?
提问by Ronald Blaschke
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.")
我有一些需要调用 Java 的本机线程。为此,我需要使用AttachCurrentThread
. 由于这个回调会经常发生,线程应该保持连接。AttachCurrentThread
多次调用是可以的(“尝试附加一个已经附加的线程是一个空操作。”)
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?
我是否必须DetachCurrentThread
在线程退出之前调用,它会自动发生,还是甚至不需要?如果我必须调用 detach 但不调用会发生什么?它会不会只是“泄漏”,或者这甚至会破坏 VM 状态?
I have checked the Java Native Interface specification, but either missed this, or it really is unspecified.
我已经检查了 Java Native Interface 规范,但要么错过了这一点,要么确实未指定。
My question applies specifically to Sun JDK 6 on Windows XP.
我的问题特别适用于 Windows XP 上的 Sun JDK 6。
回答by kdgregory
I think that the confirmation that you want is here: http://java.sun.com/javase/6/docs/technotes/guides/jni/spec/invocation.html#wp1060
我认为您想要的确认在这里: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.
附加到 VM 的本机线程在退出之前必须调用 DetachCurrentThread() 以分离自身。
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.
在实际卸载之前,VM 会一直等到当前线程是唯一的非守护程序用户线程。用户线程包括 Java 线程和附加的本机线程。