Video in progress

Strong Middle 📁 IO and NIO

How does FileChannel.transferTo achieve "zero-copy", and where does it help?

In an ordinary copy, data travels disk → kernel → user-space buffer → kernel → socket. On Linux transferTo uses sendfile to move the data inside the kernel straight to the socket: no copy into user space, fewer context switches.

📖 Answer

The classic loop:

byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) != -1) out.write(buf, 0, n);

For every chunk that is two system calls and two memory copies: from the kernel into a Java array, then back into the kernel.

Zero-copy:

try (FileChannel file = FileChannel.open(path);
     SocketChannel sock = SocketChannel.open(addr)) {
    long pos = 0, size = file.size();
    while (pos < size) {
        pos += file.transferTo(pos, size - pos, sock); // may not transfer everything in one go
    }
}

A well-known example is Kafka: the broker serves log segments to the consumer through sendfile, which is why it gets huge throughput with little CPU. Nginx serving static files works on the same principle.

Limitations:

  • with TLS, the data has to come into user space to be encrypted, so the zero-copy is lost (kernel TLS is an exception, but that is a separate topic);
  • if you need to change the data (compress, filter), it doesn't work;
  • one call may not transfer all the bytes, so the loop is required.

InputStream.transferTo(OutputStream) in Java 9+ is a different thing: it is a plain buffer loop. In some JDK versions, when both sides are files it switches to channels internally, but don't rely on that.