Video in progress
Can several threads use a single `FileChannel` together? What happens to the channel position?
Yes, FileChannel is thread-safe. But read(buf)/write(buf), which rely on the current position, wait for each other, and the position is shared by everyone. For parallel work use the positional read(buf, pos)/write(buf, pos), with each thread having its own buffer.
📖 Answer
The Javadoc says it explicitly: a channel can be used by several threads, but an operation that touches the position or changes the file size runs only one at a time. So code like this works correctly but not in parallel:
// 8 threads read from the same channel one after another: taking turns, and who gets which chunk is undefined
channel.read(buf);
The positional variants don't change the channel's position and, if the implementation allows it, run concurrently:
long offset = chunkIndex * CHUNK;
ByteBuffer local = ByteBuffer.allocate(CHUNK); // the buffer belongs to the thread
while (local.hasRemaining()) {
int n = channel.read(local, offset + local.position());
if (n < 0) break;
}
Don't forget that ByteBuffer itself is not thread-safe: giving one buffer to two threads defeats the channel's safety.
There are two unexpected cases on prod:
- Interrupt. A channel is an
InterruptibleChannel. If one thread is interrupted during IO, the channel is closed for everyone: that thread getsClosedByInterruptException, the others getAsynchronousCloseExceptionorClosedChannelException. Callingcancel(true)in an executor kills the whole channel this way. - APPEND mode. If the file was opened with
APPEND, the behavior ofwrite(buf, pos)is unspecified, so don't use positional writes on an append channel.
In practice, for reading a big file in parallel, one channel + positional reads is enough; you don't need to open a separate channel for each thread.
Sign up to mark studied questions and save your progress.