Question

Based on the documentation of java.NIO, buffers are thread-unsafe, while channels in most of the cases (FileChannel, SocketChannel etc.) are safe to be used by multiple threads. What I cannot find in the documentation is a clear description of what happens when e.g. two threads start to read from a FileChannel concurrently. Does the first operation read first N bytes, or is it possible to get first M bytes to the first channel's buffer, and then the next couple would go to the second buffer, before we context switch would read some more into the first etc. Does anyone know what the guarantees are for multithreaded access to channels?

Was it helpful?

Solution

A read "involves the file's position" and therefore blocks subsequent reads by other threads. However nothing guarantees how many bytes a read returns whether single- or multi-threaded, other than that it is greater than zero if there are bytes left to read.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top