Detecting thread interruption with JNA native wait call (Windows)

こ雲淡風輕ζ 提交于 2019-12-01 07:29:33

问题


I'm trying to write some code that performs a wait via JNA (e.g. by calling the Kernel32 function WaitForSingleObject), but I'd also like the wait to finish if Thread.interrupt() is called; I assume Java uses something like an Event object to implement interruption; is there any way of getting the Event from Java in order to use it in a call to WaitForMultipleObjects? Or is there any other way I could arrange for my wait to finish if the thread is interrupted?


回答1:


Java supports it via NIO and very few people are aware of, the class in question is abstract but that's no issue:

java.nio.channels.spi.AbstractInterruptibleChannel. It has 3 methods of interest: begin() and end(), those are final, plus that one you have to implement: "protected abstract void implCloseChannel() throws IOException" The method is going to be called from the thread invoking interrupt(), so be careful.

The use is very simple: call begin before entering the native code and end() upon return. Handling the interruption in implCloseChannel.

Happy coding!




回答2:


Having found a bit of time to do some more research, I went for a digging expedition in the OpenJDK source code this morning. It turns out that starting with the native implementation was wrong; there's a pure-Java mechanism for doing this.

The class sun.misc.SharedSecrets has a static method getJavaLangAccess(), which returns an object with a method blockedOn(Thread, sun.nio.ch.Interruptible). This can be used to arrange for Thread.interrupt() to call a method supplied by one of my own objects, at which point I can create my own interruption Event object with which I can ensure waits are terminated as required.

Doing this introduces dependencies on sun's implementation of the Java class library, but probably less so than digging through the JVM's native state to try to extract an event handle that it uses internally.



来源:https://stackoverflow.com/questions/7889161/detecting-thread-interruption-with-jna-native-wait-call-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!