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 InputStreamByteBufferreadwrite
| Type | Since | Connects to | Notable features |
|---|---|---|---|
ReadableByteChannelWritableByteChannel | Java 1.4 | Anything | The basic read and write contracts |
ScatteringByteChannelGatheringByteChannel | Java 1.4 | Files, sockets | One call reads into, or writes from, several buffers |
FileChannel | Java 1.4 | A file | Positional I/O, transferToforce |
SocketChannelServerSocketChannelDatagramChannel | Java 1.4 | Network | Non-blocking mode with a Selector |
Pipe.SourceChannelPipe.SinkChannel | Java 1.4 | Another thread | A one-way pipe inside the JVM |
SeekableByteChannel | Java 7 | Files, ZIP entries | Position and size; returned by Files.newByteChannel |
AsynchronousFileChannelAsynchronousSocketChannel | Java 7 | Files, network | Operations return a Future |
The ChannelsChannels.newChannel(inputStream)Channels.newInputStream(channel)Channels.newReader(channel, charset)FileChannel
The read, flip, write loop
Every channel copy follows the same loop: read into the buffer, flip()compact()Channels.newChannel
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:
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
, because after the last read returns -1 there may still be unwritten bytes in the buffer.buf.position() > 0 - Here each
took everything, so nothing was left over. A non-blocking socket can accept only part of a buffer.write then moves the unwritten bytes to the start, and they go out in the next round. Usingcompact() instead would throw them away.clear() - The classic mistake is writing without
. After the read, the position is 16 and the limit 16, so there is nothing between them, andflip() wrote 0 bytes without any error.write
FileChannel: scatter, gather, positions and size
A FileChannelFileChannel.open(path, options)RandomAccessFilegetChannel()
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:
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
until it is full (4 bytes) and thenh , so a fixed-size header lands in its own buffer.b 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.read(buffer, position) 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.truncate(4)
The same positional reading and writing with a simpler, older API is on the
transferTo and copying speed
transferTosendfileFiles.mismatch
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):
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
andtransferTo were the fastest in every run. Both copy in native code or in the kernel, without moving the data through a Java buffer.Files.copy- 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.
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.transferTo- 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.copytransferTotransferFrom
Memory-mapped files and the three map modes
mapMappedByteBuffercounter=0000
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:
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
: putting "0042" into the buffer changed the file, asREAD_WRITE shows.Files.readString on the buffer waits until the changed pages are on the storage device.force() : 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.PRIVATE :READ_ONLY threwput . 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.ReadOnlyBufferException- 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
File locks: between processes, not between threads
FileChannel.locktryLock
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:
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
on the whole file returnedtryLock() .null never waits;tryLock would have blocked until the range was free.lock - Inside the same JVM, a second overlapping lock did not wait or return
: it threwnull . File locks are held by the whole process, so they cannot coordinate threads. UseOverlappingFileLockException locks for that.java.util.concurrent - 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
Javadoc warns.FileLock
For a simpler "only one instance may run" check without holding a lock, see CREATE_NEW
AsynchronousFileChannel
AsynchronousFileChannelFutureCompletionHandler
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:
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
read returned 10 bytes, "first part", whenFuture was called; until then the main thread could do other work.get() - The handler read the 11 bytes of "second part" from position 11 and ran on a pool thread, not on
. Code in a handler must therefore be thread-safe.main - 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
on aFileChannelvirtual thread is often the simpler way to get the same concurrency.
Which channel feature to use
| Need | Use |
|---|---|
| Copy a file | Files.copy |
| Send a file over a socket | FileChannel.transferTo |
| Read or write at known offsets, from several threads | FileChannel.read(buf, position)write(buf, position) |
| Header and body in separate buffers | Gathering write(ByteBuffer[])read(ByteBuffer[]) |
| Random access to a large file as if it were memory | FileChannel.mapREAD_ONLYREAD_WRITE |
| Change file content in memory only | MapMode.PRIVATE |
| Keep other processes out of a file | FileChannel.locktryLock |
| Keep other threads out | A ReentrantLocksynchronized |
| Make writes durable | FileChannel.force |
| Start file reads without blocking a thread | AsynchronousFileChannel |
| Many network connections on few threads | Non-blocking SocketChannel |