根据the documentation for AsynchronousFileChannel
,
The
ByteBuffer
s used when reading or writing are not safe for use by multiple concurrent I/O operations. Furthermore, after an I/O operation is initiated then care should be taken to ensure that the buffer is not accessed until after the operation has completed.
在某些方面,这似乎比实际需要的要严格得多。从其他方面来看,似乎还不够严格。特别是:
- 您无法从写入操作中使用的
ByteBuffer
进行读取,即使写入操作不会修改缓冲区内容。 - 如果 I/O 操作仅涉及
ByteBuffer
的一部分,则无法读取或写入同一ByteBuffer
的不相交部分。 - 当
ByteBuffer
参与 I/O 操作时,您无法更改它的位置或限制。 - 它并没有说您不能在不同的 I/O 操作中使用缓冲区的两个
切片
,因为它们是引用同一底层缓冲区的两个不同的ByteBuffer
对象。它甚至没有说明切片重叠的情况。
这些观点正确吗?或者其他地方是否更准确地指定了限制?
最佳答案
根据Buffer
的文档:
Thread safety
Buffers are not safe for use by multiple concurrent threads. If a buffer is to be used by more than one thread then access to the buffer should be controlled by appropriate synchronization.
由于 ByteBuffer
没有显示线程安全的明确迹象,因此在异步 I/O 使用它时访问它可能会导致数据损坏或竞争条件。
关于java - 访问用于异步 I/O 的缓冲区到底有哪些限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34631209/