-1

I have gzip compressor which for the purpose of this question can be seen as a simple buffer.

The compressor writes into a NIO2 AsynchronousFileChannel. Once there are enough compressed bytes, the buffer is flushed and an async AsynchronousFileChannel.write() call is initiated.

Once all writes are complete, the compressor might still contain data. So I need to:

  • flush & close the compressor
  • perform one last write
  • close the AsynchronousFileChannel itself.

The documentation for AsynchronousFileChannel.close() states that

Any outstanding asynchronous operations upon this channel will complete with the exception AsynchronousCloseException

Might this include the last write submitted by the same thread just before it calls close()?

In other words, is the following safe?

AsynchronousFileChannel channel = ...
...
//Is there a chance that this write will throw an AsynchronousCloseException?
channel.write(...); 
channel.close();

or do I need to block until the last write returns?

Malt
  • 28,965
  • 9
  • 65
  • 105

1 Answers1

1

Might this include the last write submitted by the same thread just before it calls close()?

Yes, of course.

In other words, is the following safe?

No.

or do I need to block until the last write returns?

You need to do the close in the completion handler for the last write, or after you have successfully obtained its Future.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • I suspect that you're right, but is this written explicitly anywhere? – Malt Oct 24 '17 at 08:14
  • Part of it is written in the quotation you provided, and the other part is implicit in the notion of asynchronicity. – user207421 Oct 24 '17 at 08:52
  • You're right about the quotation, but the case in question is one in which the thread calling `write` is the same as the one calling `close`. I agree that in the general case, with two different threads that the answer is obvious. But since there's only one thread, and the call to `write()` completes strictly before `close()` then perhaps the `write` is no longer "outstanding". It's a long shot, but I was just wondering whether there was something more explicit written about it. – Malt Oct 24 '17 at 09:17
  • Once the `write()` has started, it is asynchronous. *Ergo* the case where the thread calling `write()` is the same as the thread calling `close()` is covered completely by your quotation. – user207421 Oct 24 '17 at 09:25