Thread interrupt not ending blocking call on input stream read

前端 未结 3 1344
时光取名叫无心
时光取名叫无心 2021-01-04 13:30

I\'m using RXTX to read data from a serial port. The reading is done within a thread spawned in the following manner:

CommPortIdentifier portIdentifier = Co         


        
3条回答
  •  盖世英雄少女心
    2021-01-04 13:58

    You can't make a stream that doesn't support interruptible I/O into an InterruptibleChannel simply by wrapping it (and, anyway, ReadableByteChannel doesn't extend InterruptibleChannel).

    You have to look at the contract of the underlying InputStream. What does SerialPort.getInputStream() say about the interruptibility of its result? If it doesn't say anything, you should assume that it ignores interrupts.

    For any I/O that doesn't explicitly support interruptibility, the only option is generally closing the stream from another thread. This may immediately raise an IOException (though it might not be an AsynchronousCloseException) in the thread blocked on a call to the stream.

    However, even this is extremely dependent on the implementation of the InputStream—and the underlying OS can be a factor too.


    Note the source code comment on the ReadableByteChannelImpl class returned by newChannel():

      private static class ReadableByteChannelImpl
        extends AbstractInterruptibleChannel       // Not really interruptible
        implements ReadableByteChannel
      {
        InputStream in;
        ⋮
    

提交回复
热议问题