Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Let's say I started a thread 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 a ExecutorService object and in is a BufferedReader object

I know you can close the socket from a different thread to interrupt this thread. But when I try to use future.cancel(true) method, even though it returns true, the thread seems still running, anybody know why? or in.readLine() cannot be interrrupted this way?

like image 206
neo Avatar asked Apr 02 '12 15:04

neo


3 Answers

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.

like image 175
Gray Avatar answered Sep 30 '22 17:09

Gray


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.

like image 28
Peter Lawrey Avatar answered Sep 30 '22 16:09

Peter Lawrey


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.

like image 44
assylias Avatar answered Sep 30 '22 18:09

assylias