FileChannel implements InterruptibleChannel, help or hindrance?

David Lloyd david.lloyd at redhat.com
Mon Mar 5 15:47:01 UTC 2018


On Mon, Mar 5, 2018 at 9:25 AM, Alan Bateman <Alan.Bateman at oracle.com> wrote:
> On 05/03/2018 15:15, David Lloyd wrote:
>>
>> :
>> In all cases, exceptionless partial reads are a perfectly
>> safe/acceptable outcome for interruption.  In fact if the API were
>> being designed from scratch today, I might even argue that a
>> zero-bytes read/write would be the preferred behavior when operations
>> are entered in an interrupted state.  Either way I don't see how
>> anything in the API (as I've proposed it) could possibly lead to data
>> loss.  AFAICT the biggest API risk is the use of bytesTransferred in
>> InterruptedIOException, which in retrospect was probably not a great
>> idea.
>
> Switch your example to writing and wrap it in an API (such as OutputStream)
> that does not tolerate short writes and you'll start to see some of the
> issues. Reading is problematic too btw, esp. if you throw an exception after
> reading bytes.

As far as I can tell, the specification of OutputStream cannot
accommodate any more lenient approaches - it's stuck with
InterruptedIOException forever.  InputStreams could possibly get away
with returning a partial read instead of throwing an exception in the
event that some data was transferred, but I don't think it really
matters at this point: users of *Stream are already required to cope
with InterruptedIOException if they care about resuming after
interruption.

But, we are talking about channels here, not Input/OutputStream.
Allowing short reads and writes is within spec for channels of all
types.  Whether channels throw an exception on interrupt when no bytes
were yet transferred, or whether they just return a 0 value, is the
only question that would need to seriously be considered, but either
behavior is preferable to killing the entire channel in any case I can
imagine.

One side benefit to not closing the channel on interrupt is that a
blocking *Stream can then safely be directly implemented in terms of a
blocking *Channel - even the ugly OutputStream case.

-- 
- DML


More information about the nio-dev mailing list