Flushable.flush() 的一般行为是阻塞直到操作完成吗?

Is the general behavior of Flushable.flush() to block until the operation is complete?

我们有一个库可以缓冲其操作以提高性能。调用者可以调用 flush() 方法来强制它开始执行操作。

但是现在,flush() 方法的实现方式是它开始异步执行操作。

也就是说,当调用者调用 flush() 方法时,它将在不同的线程中开始执行其操作,而 flush() 方法只是 returns.

这样,调用者在调用 close() 方法之前不知道操作是否完成(他们必须通过检查操作结果来确定)。

我想通过使 flush() 调用阻塞直到所有操作完成来修复它。

在这样做之前,我想确保 flush() 方法应该阻塞。但是 API 文档没有指定这样的合同。

Flushable.flush() API Doc:

Flushes this stream by writing any buffered output to the underlying stream.

OutputStream.flush() API Doc:

Flushes this output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

If the intended destination of this stream is an abstraction provided by the underlying operating system, for example a file, then flushing the stream guarantees only that bytes previously written to the stream are passed to the operating system for writing; it does not guarantee that they are actually written to a physical device such as a disk drive.

The flush method of OutputStream does nothing.

这两个文档都没有指定任何关于阻塞直到输出被写入或不被写入的内容。

但是一般的理解是什么flush(),到底是不是阻塞调用呢?

the API documentation doesn't specify a contract like that.

是的。

两个 Javadoc 引文都来自 OutputStream 系列,它本质上对所有操作都是阻塞的。如果您异步执行,则不能 'guarantee that bytes previously written to the stream are flushed'。

解决方案:不要。