AsynchronousFileChannel - 确保 close() 在写入完成后发生

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

我有 gzip 压缩器,出于这个问题的目的,可以将其视为一个简单的缓冲区。

压缩器写入 NIO2 AsynchronousFileChannel。一旦有足够的压缩字节,就会刷新缓冲区并启动异步 AsynchronousFileChannel.write() 调用。

一旦所有 写入完成,压缩器可能仍包含数据。所以我需要:

AsynchronousFileChannel.close() 的文档指出

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

这可能包括同一线程在调用 close() 之前提交的最后一次写入吗?

也就是说,下面的安全吗?

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

或者我是否需要阻塞直到最后一次写入 returns?

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

当然可以。

In other words, is the following safe?

没有

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

您需要在最后一次写入的完成处理程序中关闭,或者在您成功获取其Future后关闭。