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

Say I started a topic and I have something like this:

...//initiate all the socket connection future = executor.submit ( new Runnable() { public void run() { ... ... while ((str = in.readLine()) != null) { //do something here } } ); 

executor is an ExecutorService object and is a BufferedReader object

I know that you can close a socket from another thread to interrupt this thread. But when I try to use the future.cancel (true) method, although it returns true, the thread seems to be still running, does anyone know why? or in.readLine () cannot be interrupted this way?

+6
source share
3 answers

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

All future.cancel(true) makes a call to thread.interrupt() in the associated thread. This will trigger sleep() and wait() to throw an InterruptedException and break some special NIO channels .

But the chances are that your BufferedReader will not be interrupted, as it will most likely be read from a "normal" socket or file. As you say closing a base socket from another thread is the best way to kill such an I / O method.

+10
source

You can close the In stream to raise an IOException. Otherwise, readLine () may be locked forever.

I reviewed using JavaLangAccess.blockedOn (), but it looks pretty low.

+3
source

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

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

But if it blocks readLine execution, the only way to abort it is to close the underlying thread that will throw an IOException.

+1
source

Source: https://habr.com/ru/post/912241/


All Articles