java - 访问用于异步 I/O 的缓冲区到底有哪些限制?

标签 java asynchronous nio

根据the documentation for AsynchronousFileChannel ,

The ByteBuffers 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/

相关文章:

ios - 在等待数据的同时导航到新 View Controller 的最佳实践

c# - 在 C# 中异步解析 CSV 文件的最佳方法是什么

javascript - "throw new Error()"在 catch block 上下文中捕获

java - 如何从只有 1 个剩余字节的 ByteBuffer 中获取 Int (Java NIO)

java - NIO getParentFile().mkdir()

java - 集群环境中的单例

java - Web 上下文根是否有内置的 Spring 环境变量?

java - 使用 StaxEventItemWriter 构建重要的 XML 文件

java - JPA、XML - 无参数私有(private)构造函数是否被普遍接受?

java - 我可以使用 Java NIO 从套接字中读取可用字节吗?