Search code examples
javaasynchronousnio

What exactly are the restrictions on accessing a buffer being used for asynchronous I/O?


According to 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.

In some ways this seems much stricter than should actually be necessary. In other ways, it seems to not be strict enough. In particular:

  • You aren't allowed to read from a ByteBuffer that's being used in a write operation, even though the write operation won't modify the buffer contents.
  • If only part of a ByteBuffer is involved in an I/O operation, you can't read or write a disjoint part of the same ByteBuffer.
  • You can't change the position or limit of a ByteBuffer while it's involved in an I/O operation.
  • It doesn't say you can't use two slices of a buffer in different I/O operations, since they'd be two different ByteBuffer objects that refer to the same underlying buffer. It doesn't even say anything about the case where you have overlapping slices.

Are these points correct? Or are the restrictions more accurately specified somewhere else?


Solution

  • According to Buffer's documentation:

    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.

    Since ByteBuffer shows no explicit signs of thread safety, accessing it while it's being used by async I/O might incur data corruption or race conditions.