javanionio2

AsynchronousFileChannel - make sure that close() happens after writes are finished


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:

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?


Solution

  • 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.