Java NIO channels

A channel moves blocks of bytes between a buffer and a file, socket or pipe, and a FileChannel adds what streams cannot do: reading and writing at any position, copying inside the operating system, mapping a file into memory and locking parts of it. This page explains the channel model, runs each FileChannel feature, measures copying, and shows the locking rules that differ between processes and threads.

Contents

What a channel is

A stream, such as InputStream, moves bytes one call at a time and hides where they come from. A channel, added in Java 1.4 with the NIO API (JSR 51), is an open connection to a file, socket or pipe that moves bytes between that entity and a ByteBuffer. Every channel operation works on a buffer: read fills it from its position up to its limit, and write drains it the same way. Channels can be closed, can be interruptible, and some can be switched to non-blocking mode. The design maps closely to what the operating system offers, which is why channels can do things streams cannot.

The main channel types
TypeSinceConnects toNotable features
ReadableByteChannel, WritableByteChannelJava 1.4AnythingThe basic read and write contracts
ScatteringByteChannel, GatheringByteChannelJava 1.4Files, socketsOne call reads into, or writes from, several buffers
FileChannelJava 1.4A filePositional I/O, transferTo, mapping, locking, force
SocketChannel, ServerSocketChannel, DatagramChannelJava 1.4NetworkNon-blocking mode with a Selector
Pipe.SourceChannel, Pipe.SinkChannelJava 1.4Another threadA one-way pipe inside the JVM
SeekableByteChannelJava 7Files, ZIP entriesPosition and size; returned by Files.newByteChannel
AsynchronousFileChannel, AsynchronousSocketChannelJava 7Files, networkOperations return a Future or call a handler

The Channels utility class converts in both directions: Channels.newChannel(inputStream) wraps a stream, and Channels.newInputStream(channel) or Channels.newReader(channel, charset) wrap a channel. For buffer details such as direct buffers and byte order, see the ByteBuffer page; for non-blocking network servers, see NIO selectors. This page concentrates on the channel side, mostly FileChannel. All programs were compiled and run on JDK 21 on Linux.

The read, flip, write loop

Every channel copy follows the same loop: read into the buffer, flip() it so the bytes just read become readable, write, and compact() it so anything not yet written is kept for the next round. The program copies a 46-byte message through a 16-byte buffer, small on purpose so the loop runs several rounds, using Channels.newChannel over in-memory streams so the same code would work for a file or a socket.

Java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.StandardCharsets;

public class CopyLoop {

    public static void main(String[] args) throws IOException {
        byte[] data = "Channels move blocks of bytes through buffers.".getBytes(
                StandardCharsets.US_ASCII);
        // Channels.newChannel adapts any stream, so the loop works for files and sockets alike
        ReadableByteChannel in = Channels.newChannel(new ByteArrayInputStream(data));
        ByteArrayOutputStream sink = new ByteArrayOutputStream();
        WritableByteChannel out = Channels.newChannel(sink);

        ByteBuffer buf = ByteBuffer.allocate(16);           // small on purpose
        int round = 0;
        while (in.read(buf) != -1 || buf.position() > 0) {
            buf.flip();                                     // switch from filling to draining
            int before = buf.remaining();
            out.write(buf);                                 // may write only part of it
            System.out.printf("round %d: read up to %2d bytes, wrote %2d, left over %d%n",
                    ++round, before, before - buf.remaining(), buf.remaining());
            buf.compact();                                  // keep unwritten bytes, refill after
        }
        System.out.println("copied " + sink.size() + " of " + data.length + " bytes: "
                + sink.toString(StandardCharsets.US_ASCII));

        // The classic mistake: forgetting flip() writes nothing
        ByteBuffer wrong = ByteBuffer.allocate(16);
        Channels.newChannel(new ByteArrayInputStream(data)).read(wrong);
        ByteArrayOutputStream lost = new ByteArrayOutputStream();
        int written = Channels.newChannel(lost).write(wrong);   // position 16, limit 16
        System.out.println("write without flip(): " + written + " bytes written");
    }
}

Output:

Output
round 1: read up to 16 bytes, wrote 16, left over 0
round 2: read up to 16 bytes, wrote 16, left over 0
round 3: read up to 14 bytes, wrote 14, left over 0
copied 46 of 46 bytes: Channels move blocks of bytes through buffers.
write without flip(): 0 bytes written
  • The 46 bytes took three rounds: 16, 16 and 14. The loop condition also continues while buf.position() > 0, because after the last read returns -1 there may still be unwritten bytes in the buffer.
  • Here each write took everything, so nothing was left over. A non-blocking socket can accept only part of a buffer. compact() then moves the unwritten bytes to the start, and they go out in the next round. Using clear() instead would throw them away.
  • The classic mistake is writing without flip(). After the read, the position is 16 and the limit 16, so there is nothing between them, and write wrote 0 bytes without any error.

FileChannel: scatter, gather, positions and size

A FileChannel is the channel for a file, opened with FileChannel.open(path, options) or obtained from a RandomAccessFile or file stream with getChannel(). The program stores a small record as a 4-byte length field followed by "hello world" (11 bytes). It writes from two buffers in one call, reads back into two buffers, reads one word at a fixed offset, copies the file, and then changes its size.

Java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class FileChannelOps {

    public static void main(String[] args) throws IOException {
        Path dir = Files.createTempDirectory("channels");
        Path file = dir.resolve("message.bin");

        // Gather write: header and body from two buffers in one call
        ByteBuffer header = ByteBuffer.allocate(4).putInt(11).flip();   // body length
        ByteBuffer body = ByteBuffer.wrap("hello world".getBytes(StandardCharsets.US_ASCII));
        try (FileChannel ch = FileChannel.open(file, StandardOpenOption.CREATE,
                StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
            long written = ch.write(new ByteBuffer[] {header, body});
            System.out.println("gather write: " + written + " bytes, file size " + ch.size());
        }

        // Scatter read: fill the header buffer first, then the body buffer
        ByteBuffer h = ByteBuffer.allocate(4);
        ByteBuffer b = ByteBuffer.allocate(11);
        try (FileChannel ch = FileChannel.open(file, StandardOpenOption.READ)) {
            ch.read(new ByteBuffer[] {h, b});
            int length = h.flip().getInt();
            String text = StandardCharsets.US_ASCII.decode(b.flip()).toString();
            System.out.println("scatter read: length field " + length + ", body \"" + text + "\"");

            // Positional read: does not move the channel's position
            ByteBuffer word = ByteBuffer.allocate(5);
            ch.read(word, 4 + 6);
            System.out.println("read at offset 10: \""
                    + StandardCharsets.US_ASCII.decode(word.flip()) + "\", channel position still "
                    + ch.position());
        }

        // transferTo: copy between channels, often done inside the OS without user-space copies
        Path copy = dir.resolve("copy.bin");
        try (FileChannel src = FileChannel.open(file, StandardOpenOption.READ);
             FileChannel dst = FileChannel.open(copy, StandardOpenOption.CREATE,
                     StandardOpenOption.WRITE)) {
            long moved = src.transferTo(0, src.size(), dst);
            System.out.println("transferTo copied " + moved + " bytes, identical: "
                    + (Files.mismatch(file, copy) == -1));
        }

        // size, truncate and writing past the end
        try (FileChannel ch = FileChannel.open(copy, StandardOpenOption.WRITE)) {
            ch.truncate(4);
            System.out.println("after truncate(4): size " + ch.size());
            ch.write(ByteBuffer.wrap(new byte[] {'!'}), 9);
            System.out.println("after a write at position 9: size " + ch.size()
                    + ", bytes 4 to 8 are zeros: " + (Files.readAllBytes(copy)[6] == 0));
        }
        Files.delete(copy);
        Files.delete(file);
        Files.delete(dir);
    }
}

Output:

Output
gather write: 15 bytes, file size 15
scatter read: length field 11, body "hello world"
read at offset 10: "world", channel position still 15
transferTo copied 15 bytes, identical: true
after truncate(4): size 4
after a write at position 9: size 10, bytes 4 to 8 are zeros: true
  • Gather writes the header and body back to back, 4 + 11 = 15 bytes, without copying them into one array first. Network protocols use the same trick to send a header and a payload kept in separate buffers.
  • Scatter fills h until it is full (4 bytes) and then b, so a fixed-size header lands in its own buffer.
  • read(buffer, position) reads from an absolute offset. "world" starts at 4 + 6 = 10. This form does not move the channel's own position, which stays at 15 where the scatter read left it, so several threads can do positional reads on one channel at the same time.
  • truncate(4) cut the copy to 4 bytes. A write at position 9 then grew it to 10 bytes and filled the gap, bytes 4 to 8, with zeros. On file systems with sparse file support such a gap takes no disk space.

The same positional reading and writing with a simpler, older API is on the RandomAccessFile page; the text-specific side, decoding the bytes you read, is on reading a text file.

transferTo and copying speed

transferTo asks the operating system to move bytes from one channel to another directly. On Linux, from a file to a socket it can use sendfile, so the data never passes through Java memory at all. The program copies a 300 MB file five ways, each into a newly created file, best of 3 runs after one warm-up. It works in the current directory, a real disk, and checks every copy with Files.mismatch.

Java
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Random;

public class CopySpeed {

    interface Copier {
        void copy(Path src, Path dst) throws IOException;
    }

    static void streams(Path src, Path dst) throws IOException {
        try (InputStream in = Files.newInputStream(src);
             OutputStream out = Files.newOutputStream(dst)) {
            byte[] buf = new byte[64 * 1024];
            int n;
            while ((n = in.read(buf)) != -1) {
                out.write(buf, 0, n);
            }
        }
    }

    static void channelLoop(Path src, Path dst, ByteBuffer buf) throws IOException {
        try (FileChannel in = FileChannel.open(src, StandardOpenOption.READ);
             FileChannel out = FileChannel.open(dst, StandardOpenOption.CREATE,
                     StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
            buf.clear();
            while (in.read(buf) != -1) {
                buf.flip();
                while (buf.hasRemaining()) {
                    out.write(buf);
                }
                buf.clear();
            }
        }
    }

    static void transferTo(Path src, Path dst) throws IOException {
        try (FileChannel in = FileChannel.open(src, StandardOpenOption.READ);
             FileChannel out = FileChannel.open(dst, StandardOpenOption.CREATE,
                     StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
            long pos = 0;
            long size = in.size();
            while (pos < size) {                            // may transfer less than asked
                pos += in.transferTo(pos, size - pos, out);
            }
        }
    }

    static void measure(String label, Path src, Path dst, Copier c) throws IOException {
        Files.deleteIfExists(dst);
        c.copy(src, dst);                                   // warm-up
        long best = Long.MAX_VALUE;
        for (int i = 0; i < 3; i++) {
            Files.delete(dst);                              // every copy creates a new file
            long start = System.nanoTime();
            c.copy(src, dst);
            best = Math.min(best, System.nanoTime() - start);
        }
        if (Files.mismatch(src, dst) != -1) {
            throw new IllegalStateException(label + " produced a different file");
        }
        System.out.printf("%-38s %5d ms%n", label, best / 1000000);
    }

    public static void main(String[] args) throws IOException {
        Path src = Path.of("copy-src.bin");                 // working directory, a real disk
        Path dst = Path.of("copy-dst.bin");
        byte[] block = new byte[1 << 20];
        new Random(1).nextBytes(block);
        try (OutputStream out = Files.newOutputStream(src)) {
            for (int i = 0; i < 300; i++) {
                out.write(block);
            }
        }
        System.out.println("copying " + Files.size(src) / (1 << 20) + " MB, best of 3");
        ByteBuffer heap = ByteBuffer.allocate(64 * 1024);
        ByteBuffer direct = ByteBuffer.allocateDirect(64 * 1024);
        measure("InputStream/OutputStream, 64 KB array", src, dst, CopySpeed::streams);
        measure("FileChannel loop, 64 KB heap buffer", src, dst,
                (s, d) -> channelLoop(s, d, heap));
        measure("FileChannel loop, 64 KB direct buffer", src, dst,
                (s, d) -> channelLoop(s, d, direct));
        measure("FileChannel.transferTo", src, dst, CopySpeed::transferTo);
        measure("Files.copy", src, dst,
                (s, d) -> Files.copy(s, d));
        Files.delete(src);
        Files.delete(dst);
    }
}

Output (rough comparison on a 2-CPU Linux VM with SSD storage, JDK 21; absolute times will differ on yours):

Output
copying 300 MB, best of 3
InputStream/OutputStream, 64 KB array    107 ms
FileChannel loop, 64 KB heap buffer      108 ms
FileChannel loop, 64 KB direct buffer    116 ms
FileChannel.transferTo                    91 ms
Files.copy                                86 ms
  • transferTo and Files.copy were the fastest in every run. Both copy in native code or in the kernel, without moving the data through a Java buffer.
  • The three user-space loops were in the same range as each other. Since all of them copy through the page cache, memory bandwidth limits all five, and the gap is a few tens of percent rather than several times.
  • transferTo may move fewer bytes than asked, so the program loops until the whole size is done. A single call is a common bug with large files.
  • Overwriting an existing target file, instead of creating a new one as here, made every timing on this machine noisier and slower. Measure the case your program really has.

For copying files, Files.copy is the simplest choice and as fast as anything here. transferTo and transferFrom earn their place when one side is a socket.

Memory-mapped files and the three map modes

map makes a region of a file appear as a MappedByteBuffer. Reading the buffer reads the file, and the operating system loads pages on demand from its cache; nothing is copied into the Java heap. The mode decides what writes do. The program maps a 12-byte file holding counter=0000 in each mode and changes the counter.

Java
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.ReadOnlyBufferException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class MappedModes {

    public static void main(String[] args) throws IOException {
        Path file = Files.createTempFile("mapped", ".dat");
        MappedByteBuffer keep;
        Files.writeString(file, "counter=0000");

        try (FileChannel ch = FileChannel.open(file, StandardOpenOption.READ,
                StandardOpenOption.WRITE)) {
            // READ_WRITE: writing to memory changes the file
            MappedByteBuffer rw = ch.map(MapMode.READ_WRITE, 0, ch.size());
            rw.put(8, "0042".getBytes(StandardCharsets.US_ASCII));
            rw.force();                                     // like FileChannel.force for the region
            System.out.println("after READ_WRITE put:  " + Files.readString(file));

            // PRIVATE: copy-on-write, changes stay in this buffer only
            MappedByteBuffer priv = ch.map(MapMode.PRIVATE, 0, ch.size());
            priv.put(8, "9999".getBytes(StandardCharsets.US_ASCII));
            byte[] seen = new byte[(int) ch.size()];
            priv.get(0, seen);
            System.out.println("PRIVATE buffer sees:   " + new String(seen,
                    StandardCharsets.US_ASCII));
            System.out.println("file after PRIVATE:    " + Files.readString(file));

            // READ_ONLY: put is rejected
            MappedByteBuffer ro = ch.map(MapMode.READ_ONLY, 0, ch.size());
            try {
                ro.put(0, (byte) 'C');
            } catch (ReadOnlyBufferException e) {
                System.out.println("READ_ONLY put:         ReadOnlyBufferException");
            }

            // The other mappings see writes made through the channel
            ch.write(java.nio.ByteBuffer.wrap("C".getBytes(StandardCharsets.US_ASCII)), 0);
            System.out.println("READ_ONLY buffer after a channel write starts with: "
                    + (char) ro.get(0));

            // Mapping past the end grows the file
            MappedByteBuffer grown = ch.map(MapMode.READ_WRITE, 0, 4096);
            System.out.println("after mapping 4096 bytes, file size: " + ch.size()
                    + ", mapped capacity: " + grown.capacity());
            keep = rw;
        }
        byte[] again = new byte[12];
        keep.get(0, again);
        System.out.println("read through the mapping after the channel was closed: "
                + new String(again, StandardCharsets.US_ASCII));
        Files.delete(file);
    }
}

Output:

Output
after READ_WRITE put:  counter=0042
PRIVATE buffer sees:   counter=9999
file after PRIVATE:    counter=0042
READ_ONLY put:         ReadOnlyBufferException
READ_ONLY buffer after a channel write starts with: C
after mapping 4096 bytes, file size: 4096, mapped capacity: 4096
read through the mapping after the channel was closed: Counter=0042
  • READ_WRITE: putting "0042" into the buffer changed the file, as Files.readString shows. force() on the buffer waits until the changed pages are on the storage device.
  • PRIVATE: copy-on-write. The buffer saw "9999", but the file kept "0042". Use it to modify a file's content in memory without changing the file.
  • READ_ONLY: put threw ReadOnlyBufferException. But the mapping is a live view: after a normal channel write of "C" at position 0, the read-only buffer saw "C" too, because all of them share the operating system's pages.
  • Mapping 4,096 bytes of a 12-byte file opened for writing grew the file to 4,096 bytes. The new bytes are unspecified by the Javadoc, so do not rely on their content.
  • The mapping stayed usable after the channel was closed: the last line read "Counter=0042" through it. A mapping lasts until the buffer is garbage collected, and Java has no public method to unmap it. On Windows this means a mapped file often cannot be deleted or truncated until then.

One buffer maps at most 2 GB. For larger files and for measurements of mapped scanning, see handling large files.

File locks: between processes, not between threads

FileChannel.lock and tryLock lock a byte range of a file, or the whole file, for the Java process. Locks are exclusive or shared. The program locks bytes 0 to 99 of a 200-byte file and starts a second JVM that tries to lock a different range and then the whole file. It then tries a second lock in its own JVM.

Java
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.List;

public class FileLocks {

    // Runs in a second JVM: tries to lock the file and reports what happened
    static void child(Path file) throws IOException {
        try (FileChannel ch = FileChannel.open(file, StandardOpenOption.WRITE)) {
            FileLock region = ch.tryLock(100, 50, false);
            System.out.println("  other process, tryLock(bytes 100-149): "
                    + (region == null ? "null" : "acquired"));
            if (region != null) {
                region.release();
            }
            FileLock whole = ch.tryLock();
            System.out.println("  other process, tryLock() on the whole file: "
                    + (whole == null ? "null (held by someone else)" : "acquired"));
        }
    }

    static void runChild(Path file) throws IOException, InterruptedException {
        String java = ProcessHandle.current().info().command().orElse("java");
        Process p = new ProcessBuilder(List.of(java, "-cp", System.getProperty("java.class.path"),
                "FileLocks", file.toString())).redirectErrorStream(true).start();
        p.getInputStream().transferTo(System.out);
        p.waitFor();
    }

    public static void main(String[] args) throws Exception {
        if (args.length == 1) {
            child(Path.of(args[0]));
            return;
        }
        Path file = Files.createTempFile("locked", ".dat");
        Files.write(file, new byte[200]);

        try (FileChannel ch = FileChannel.open(file, StandardOpenOption.READ,
                StandardOpenOption.WRITE)) {
            System.out.println("1. this process holds an exclusive lock on bytes 0-99");
            try (FileLock lock = ch.lock(0, 100, false)) {
                System.out.println("  valid: " + lock.isValid() + ", shared: " + lock.isShared());
                runChild(file);
                try {
                    ch.tryLock(0, 100, false);
                } catch (OverlappingFileLockException e) {
                    System.out.println("  same JVM, second lock: OverlappingFileLockException");
                }
            }
            System.out.println("2. lock released");
            runChild(file);
        }
        Files.delete(file);
    }
}

Output:

Output
1. this process holds an exclusive lock on bytes 0-99
  valid: true, shared: false
  other process, tryLock(bytes 100-149): acquired
  other process, tryLock() on the whole file: null (held by someone else)
  same JVM, second lock: OverlappingFileLockException
2. lock released
  other process, tryLock(bytes 100-149): acquired
  other process, tryLock() on the whole file: acquired
  • While the first process held bytes 0 to 99, the other process could lock bytes 100 to 149, because the ranges do not overlap, but tryLock() on the whole file returned null. tryLock never waits; lock would have blocked until the range was free.
  • Inside the same JVM, a second overlapping lock did not wait or return null: it threw OverlappingFileLockException. File locks are held by the whole process, so they cannot coordinate threads. Use java.util.concurrent locks for that.
  • After the lock was released, the other process got both locks.
  • On Linux and macOS these locks are advisory: they stop only programs that also ask for locks. A program that simply opens and writes the file is not blocked. On Windows they are mandatory. Closing the channel releases its locks, and on some systems closing any channel to the file releases all of the JVM's locks on it, as the FileLock Javadoc warns.

For a simpler "only one instance may run" check without holding a lock, see CREATE_NEW on the file open options page.

AsynchronousFileChannel

AsynchronousFileChannel (Java 7) starts a read or write and returns immediately. The result arrives as a Future or through a CompletionHandler that runs on a thread pool. Every operation takes an explicit position, since several operations may be in progress at once. The program reads the two halves of a short file both ways, then writes at position 0.

Java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

public class AsyncFile {

    public static void main(String[] args) throws Exception {
        Path file = Files.createTempFile("async", ".txt");
        Files.writeString(file, "first part|second part");

        try (AsynchronousFileChannel ch = AsynchronousFileChannel.open(file,
                StandardOpenOption.READ, StandardOpenOption.WRITE)) {
            // Style 1: a Future, collected later
            ByteBuffer first = ByteBuffer.allocate(10);
            Future<Integer> pending = ch.read(first, 0);
            System.out.println("read started; this thread is free until it calls get()");
            int n = pending.get();
            System.out.println("Future: " + n + " bytes: "
                    + StandardCharsets.US_ASCII.decode(first.flip()));

            // Style 2: a CompletionHandler, called on a pool thread
            CountDownLatch done = new CountDownLatch(1);
            ByteBuffer second = ByteBuffer.allocate(11);
            ch.read(second, 11, "second", new CompletionHandler<Integer, String>() {
                @Override
                public void completed(Integer bytes, String tag) {
                    System.out.println("CompletionHandler (" + tag + "): " + bytes + " bytes: "
                            + StandardCharsets.US_ASCII.decode(second.flip())
                            + ", on the main thread? "
                            + Thread.currentThread().getName().equals("main"));
                    done.countDown();
                }

                @Override
                public void failed(Throwable e, String tag) {
                    System.out.println(tag + " failed: " + e);
                    done.countDown();
                }
            });
            done.await();

            // Writes always take a position: there is no "current position"
            int w = ch.write(ByteBuffer.wrap("FIRST".getBytes(StandardCharsets.US_ASCII)), 0)
                    .get();
            System.out.println("wrote " + w + " bytes at 0: " + Files.readString(file));
        }
        Files.delete(file);
    }
}

Output:

Output
read started; this thread is free until it calls get()
Future: 10 bytes: first part
CompletionHandler (second): 11 bytes: second part, on the main thread? false
wrote 5 bytes at 0: FIRST part|second part
  • The Future read returned 10 bytes, "first part", when get() was called; until then the main thread could do other work.
  • The handler read the 11 bytes of "second part" from position 11 and ran on a pool thread, not on main. Code in a handler must therefore be thread-safe.
  • On Linux, the JDK implements file channels of this kind with a thread pool that performs ordinary blocking reads, so they do not make file access faster. Their value is the programming model. Since Java 21, a blocking FileChannel on a virtual thread is often the simpler way to get the same concurrency.

Which channel feature to use

Choosing a channel feature
NeedUse
Copy a fileFiles.copy
Send a file over a socketFileChannel.transferTo, looping until all bytes are sent
Read or write at known offsets, from several threadsFileChannel.read(buf, position) and write(buf, position)
Header and body in separate buffersGathering write(ByteBuffer[]) and scattering read(ByteBuffer[])
Random access to a large file as if it were memoryFileChannel.map, READ_ONLY or READ_WRITE
Change file content in memory onlyMapMode.PRIVATE
Keep other processes out of a fileFileChannel.lock or tryLock
Keep other threads outA ReentrantLock or synchronized, not a file lock
Make writes durableFileChannel.force; see writing a text file
Start file reads without blocking a threadAsynchronousFileChannel, or a blocking channel on a virtual thread
Many network connections on few threadsNon-blocking SocketChannel with a Selector