Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

What does FileChannel.transferTo do, and why can it be faster than reading into a buffer and writing to a socket? What limits does it have?

FileChannel.transferTo(position, count, target) asks the operating system to move bytes from a file straight to another channel, using sendfile on Linux when the target is a socket. The data goes from the kernel's page cache to the socket without being copied into the JVM, which saves CPU, memory bandwidth and system calls. Its limits are that it may move fewer bytes than asked, so we must loop, and that TLS in the JVM breaks the shortcut because the bytes have to be encrypted in user space.

Why this question is asked

Serving files is one of the most common jobs a backend does: downloads, static assets, media, log or message segments. Done the obvious way, the CPU spends most of its time copying the same bytes between buffers. Kafka's ability to serve consumers at network speed is partly built on avoiding those copies. Interviewers ask about transferTo to see whether we understand what happens below the Java API, and whether we know the conditions under which the speedup disappears. In this answer, we will recap the page cache and user space, follow the bytes through the classic read-and-write loop, follow them through transferTo, write a correct transfer loop, and then go through its limits.

1A Quick Recap: Kernel Space, User Space and the Page Cache

Our Java program runs in user space. The operating system kernel runs in kernel space, and only the kernel can touch the disk and the network card. Whenever we read a file, the kernel first loads it into the page cache, its in-memory copy of recently used file data, and then copies the requested bytes into a buffer that our program owns. Writing to a socket works the other way: our bytes are copied into the kernel's socket buffer, and the network card sends them from there.

Each crossing between user space and kernel space is a system call, with a context switch, and each copy uses CPU time and memory bandwidth. For a single small request this is nothing. For a server pushing 10 Gbit/s of files, it is a large share of the CPU.

2Following the Bytes Through a Read-and-Write Loop

Here is the obvious way to send a file to a socket.

Java
try (InputStream in = Files.newInputStream(path);
OutputStream out = socket.getOutputStream()) {
byte[] buf = new byte[64 * 1024];
int n;
while ((n = in.read(buf)) != -1) { // copy: page cache -> our buffer
out.write(buf, 0, n); // copy: our buffer -> socket buffer
}
}

For every 64 KB chunk, the disk controller copies data into the page cache (by DMA, direct memory access, without the CPU), the CPU copies it into our byte array, the CPU copies it back into the kernel's socket buffer, and the network card copies it out by DMA. That is four copies and at least two system calls per chunk, and the two CPU copies are pure waste: our program never looks at the bytes. In Java there can even be an extra copy, because heap arrays are first copied through a temporary direct buffer.

3What transferTo Does Instead

transferTo hands the whole job to the kernel. On Linux, for a file-to-socket transfer, the JDK calls sendfile(), which tells the kernel to move bytes from the file's page cache to the socket directly. The bytes never enter user space.

Java
try (FileChannel file = FileChannel.open(path, StandardOpenOption.READ);
SocketChannel socket = SocketChannel.open(new InetSocketAddress("client.example", 9000))) {
long size = file.size(); // e.g. 1_073_741_824 (1 GiB)
long pos = 0;
while (pos < size) {
long sent = file.transferTo(pos, size - pos, socket); // may be less than asked
pos += sent;
}
}
Step throughBytes on the way to the socket
DiskPage cacheJVM bufferSocket bufferNIC
DMA copy (both approaches)
read(): CPU copy into user space
write(): CPU copy back to the kernel
transferTo/sendfile: stays in the kernel
DMA copy to the network card

5 messages in order. Play them, or step through them one at a time.

The read-and-write loop takes the two middle steps; transferTo replaces them with one in-kernel move, or none with scatter-gather DMA.

The CPU copies drop from two to at most one (the kernel may still copy from the page cache into the socket buffer), and on network cards that support scatter-gather DMA, the card reads straight from the page cache, so the CPU copies nothing. The context switches drop too, because one call can move a large range. For a busy static file server this frees a lot of CPU and memory bandwidth. Kafka uses exactly this to send log segments to consumers: the broker never parses the messages, it just ships byte ranges from the segment file to the socket.

4Limit 1: It May Transfer Fewer Bytes Than Requested

The return value is the number of bytes actually moved, and it can be less than count. On Linux a single sendfile call moves at most about 2 GB, so a 5 GB file needs several calls. With a non-blocking socket, transferTo returns as soon as the socket's send buffer is full, sometimes returning 0. That is why the code above loops. In a selector-based server, a return of 0 means we should register OP_WRITE and continue when the socket has room, rather than spinning in the loop.

Notice also that transferTo does not move the file channel's own position; we pass the position explicitly and advance it ourselves. That makes it safe to serve the same FileChannel to several clients at once, each with its own position.

5Limit 2: TLS and Other Cases Where Zero Copy Disappears

Zero copy only works if nobody needs to look at or change the bytes. TLS encryption does: with an SSLEngine, as used by Tomcat, Netty or Java's HTTPS client, the plaintext must be read into user space, encrypted, and written out. transferTo to a TLS socket either is not possible or falls back to an ordinary copy. Kafka has the same trade-off: brokers with TLS listeners lose the zero-copy path. Linux has kernel TLS (kTLS), where the kernel encrypts after the handshake, which can keep sendfile working; whether a Java stack can use it depends on the library and platform, so check your version.

Other cases fall back too. If the operating system or the target channel type does not support the shortcut, the JDK silently copies through a buffer, so the call still works, just without the benefit. Compression on the fly (gzip responses) also needs the bytes in user space. And if another process truncates the file during the transfer, we get fewer bytes than expected, so the loop should stop when transferTo returns 0 and the position has passed the file's current size.

When transferTo is really zero copy
SituationResult
File to plain TCP socket on Linuxsendfile, no user-space copy
Single call over about 2 GBpartial transfer; loop needed
Non-blocking socket with a full send bufferreturns early, possibly 0
TLS in the JVM (SSLEngine)bytes must be encrypted in user space
Kernel TLS, gzip, unsupported channeldepends on platform, or falls back to copying

6Follow-up questions

What is the difference between transferTo and transferFrom?

transferTo is called on the file channel and pushes its bytes into a target channel, which is the natural way to send a file to a socket. transferFrom is called on the file channel and pulls bytes from a source channel into the file, which suits writing a download to disk. Between two FileChannels, either may use an in-kernel copy such as copy_file_range on Linux.

Is a memory-mapped file the same as zero copy?

Not quite. FileChannel.map maps the page cache into our address space, so reading the file does not copy it into a separate buffer. But writing that mapped buffer to a socket still copies it into the socket buffer. Mapping helps when we need to look at the data; transferTo helps when we only forward it.

Why does Kafka care so much about this?

A broker mostly forwards bytes that producers already wrote. Because consumers read recent data that is usually still in the page cache, sendfile lets the broker serve many consumers at network speed with little CPU. That is also why Kafka keeps the on-disk format identical to the wire format: no conversion means nothing needs to enter user space.

7Conclusion

In this answer, we saw that the read-and-write loop copies every byte into the JVM and back out, while transferTo asks the kernel to move bytes from the page cache to the socket itself, using sendfile on Linux. That saves CPU copies, memory bandwidth and system calls, which is why Kafka and static file servers rely on it. We also saw its limits: it can transfer fewer bytes than requested, so we loop, and TLS in user space, compression or unsupported platforms bring the copies back.

What to say in the interviewAbout 100 seconds aloud

Open with

transferTo tells the operating system to move bytes from a file to another channel without the data passing through my program. If I send a file with a read-write loop, each chunk is copied by DMA into the page cache, then by the CPU into my Java buffer, then by the CPU again into the socket buffer, then by DMA to the network card, with system calls and context switches for each chunk.

Then, if they want more

My code never looks at the bytes, so the two CPU copies are wasted. With transferTo to a socket on Linux, the JDK uses sendfile, and the kernel moves the bytes from the page cache to the socket directly; with scatter-gather DMA the CPU copies nothing at all.

That is how Kafka serves consumers cheaply: it ships log segment bytes straight from the page cache. There are limits. It returns how many bytes it moved, which can be fewer than I asked for, about 2 GB per call on Linux or less when a non-blocking socket's buffer fills, so I always loop on the position.

It only helps when nobody needs to touch the data: TLS done in the JVM has to read and encrypt the bytes in user space, and so does gzip, so the zero-copy path disappears, unless kernel TLS is in play, which depends on the platform. And if the platform does not support it, the JDK quietly falls back to copying.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What does FileChannel.transferTo do, and why can it be faster than reading into a buffer...": https://scrivio-interview-library.netlify.app/java/io-and-nio/59aa3007ae/