Detecting thread interruption with JNA native wait call (Windows)

Deadly 提交于 2019-12-01 10:54:21

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!

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.

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