Can you interrupt BufferedReader.readLine() with Future.cancel(true)?

倖福魔咒の 提交于 2019-12-04 07:22:27

Can you interrupt BufferedReader.readLine() with Future.cancel(true)?

All future.cancel(true) does is to call thread.interrupt() on the associated thread. This will cause sleep() and wait() operations to throw an InterruptedException and will interrupt some special NIO channels.

But chances are your BufferedReader will not be interrupted since it is most likely reading from a "normal" socket or file. As you mention, closing the underlying socket from a different thread is the best way to kill such an IO method.

You can close the in stream to trigger an IOException. Otherwise a readLine() can block forever.

I have looked at using JavaLangAccess.blockedOn() but it looks rather low level.

readLine does not throw InterruptedException so it will not be affected if the thread it runs in is interrupted. You need to explicitly check the interrupted status of the thread:

        while ((str = in.readLine()) != null)
        {
            if (Thread.interrupted()) {
                //You can deal with the interruption here
            }
        }

But if it blocks while executing readLine , the only way to interrupt it is to close the underlying stream which will throw an IOException.

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