使用 directbytebuffer 提升 io 性能的核心做法是绕过 jvm 堆内存,直接在操作系统内核空间分配内存。通过调用 bytebuffer.allocatedirect() 创建实例,并在 filechannel 的 read() 或 write() 方法中直接传入该缓冲区,可以实现零拷贝(zero-copy)效果,减少数据在用户态与内核态之间的复制次数。

如何创建 DirectByteBuffer 并配置 FileChannel
要开始使用,首先需要实例化一个直接字节缓冲区,然后打开文件通道并将两者关联。具体步骤是先调用 ByteBuffer.allocateDirect(capacity) 获取缓冲对象,接着使用 RandomAccessFile 或 FileChannel.open() 获取 FileChannel 实例。最后,将缓冲区置于准备状态(如调用 clear()),并执行读写操作。这种配置方式确保了底层系统调用直接使用分配的 native 内存地址,避免了传统堆内缓冲区的额外拷贝开销。

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class DirectIODemo {
public static void main(String[] args) throws Exception {
// 1. 创建 DirectByteBuffer,容量为 1MB
int capacity = 1024 * 1024;
ByteBuffer buffer = ByteBuffer.allocateDirect(capacity);
// 2. 打开文件通道
try (RandomAccessFile raf = new RandomAccessFile("test.dat", "rw");
FileChannel channel = raf.getChannel()) {
// 3. 清空缓冲区,准备写入
buffer.clear();
// 4. 写入数据:channel.write(buffer) 直接使用 DirectMemory
// 这里模拟写入一些数据到缓冲区
for (int i = 0; i <p>运行上述代码,控制台将输出实际写入和读取的字节数。对于 1MB 的文件,预期输出为:<br><code>Wrote: 1048576 bytes</code><br><code>Read: 1048576 bytes</code><br>这验证了 <code>FileChannel</code> 能够直接与 <code>DirectByteBuffer</code> 交互,无需经过 JVM 堆内存中转。</p><h2>DirectByteBuffer 与传统 HeapByteBuffer 的性能差异在哪里</h2><p>性能差异主要体现在内存复制的次数和 GC 压力上。传统 <code>HeapByteBuffer</code> 位于 JVM 堆中,当进行文件 IO 时,JVM 通常需要将数据从堆内存复制到内核空间的临时缓冲区,或者反之,这涉及两次内存拷贝。而 <code>DirectByteBuffer</code> 分配的内存位于堆外,操作系统可以直接访问这块内存区域进行 DMA(直接内存访问)传输,从而减少了用户态到内核态的数据搬运。此外,由于不占用堆内存,它不会增加 Young GC 的频率,适合处理大文件或高并发场景下的长生命周期数据。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill13095" title="Build Java agent transport gateways with Atmosphere"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20e352aa140.jpg" alt="Build Java agent transport gateways with Atmosphere" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill13095" title="Build Java agent transport gateways with Atmosphere" class="overflowclass">Build Java agent transport gateways with Atmosphere</a>
<p class="overflowclass">使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。</p>
</div>
<a rel="nofollow" href="/xiazai/skill13095" title="Build Java agent transport gateways with Atmosphere" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><p><img src="https://img.php.cn/upload/article/001/242/473/179489744394638.png?x-oss-process=image/resize,p_40" alt="Java NIO 怎么用 DirectByteBuffer 提升 IO 性能"></p><pre class="brush:php;toolbar:false;">import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Arrays;
public class ComparisonDemo {
public static void main(String[] args) throws Exception {
int size = 1024 * 1024; // 1MB
byte[] data = new byte[size];
Arrays.fill(data, (byte) 'A');
// 测试 Heap Buffer
ByteBuffer heapBuf = ByteBuffer.allocate(size);
heapBuf.put(data);
heapBuf.flip();
long startHeap = System.nanoTime();
try (RandomAccessFile rafH = new RandomAccessFile("heap_test.dat", "rw");
FileChannel chH = rafH.getChannel()) {
chH.write(heapBuf);
}
long timeHeap = System.nanoTime() - startHeap;
// 测试 Direct Buffer
ByteBuffer directBuf = ByteBuffer.allocateDirect(size);
directBuf.put(data);
directBuf.flip();
long startDirect = System.nanoTime();
try (RandomAccessFile rafD = new RandomAccessFile("direct_test.dat", "rw");
FileChannel chD = rafD.getChannel()) {
chD.write(directBuf);
}
long timeDirect = System.nanoTime() - startDirect;
System.out.println("Heap Time: " + timeHeap + " ns");
System.out.println("Direct Time: " + timeDirect + " ns");
}
}
在典型的大文件写入场景下,Direct Time 通常显著小于 Heap Time。具体数值取决于硬件和系统负载,但趋势是直接的内存映射带来了更低的延迟。注意,小数据量时由于分配开销,Direct Buffer 可能略慢,但在 MB 级别以上优势明显。
DirectByteBuffer 在什么条件下会触发 OutOfMemoryError
DirectByteBuffer 的内存分配不受 JVM 堆大小(-Xmx)限制,而是受操作系统可用的本地内存(Native Memory)限制。当尝试分配超过剩余可用本地内存的缓冲区时,JVM 会抛出 java.lang.OutOfMemoryError: Direct buffer memory。这通常发生在程序持续分配大量 Direct Buffer 而未及时释放,或者系统整体内存压力过大时。即使堆内存充足,只要本地内存耗尽,就会报错。因此,需要监控 java.nio.BufferPool 或直接内存使用情况,并通过 -XX:MaxDirectMemorySize 参数显式限制最大直接内存大小,以防止影响系统稳定性。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










