1

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?

user253751
  • 57,427
  • 7
  • 48
  • 90

1 Answers1

0

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.

Community
  • 1
  • 1
bit2shift
  • 656
  • 1
  • 9
  • 17
  • `AsynchronousFileChannel` could be using a direct `ByteBuffer` - huh? The *application* allocates the buffer; the application knows what size the buffer is and whether it's a direct buffer. – user253751 Mar 12 '16 at 04:49
  • @immibis my bad, I didn't look well at the javadoc. Now I know, `ByteBuffer` isn't lockable, so you can corrupt the data while it's being read/written from/to the file. I'll edit my answer. – bit2shift Mar 12 '16 at 05:03