直接缓冲区性能优势在哪里
java nio 中直接缓冲区(direct buffer)的性能优势主要体现在避免了用户态到内核态之间的数据拷贝,从而在处理大规模 i/o 操作时显著降低延迟并提高吞吐量。实现这一优势的关键在于使用 bytebuffer.allocatedirect() 创建缓冲区,并通过 filechannel 的 transferto() 或 transferfrom() 方法将数据直接从内核空间传输到堆外内存,或者反之。这种机制利用了操作系统的零拷贝特性,使得数据无需在 jvm 堆内缓冲区和内核缓冲区之间来回复制。

直接缓冲区与堆内缓冲区的对比场景
在需要频繁进行网络数据传输或文件读写且数据量较大的场景下,直接缓冲区相比堆内缓冲区具有更低的 CPU 开销和更高的处理效率。通过对比使用 ByteBuffer.allocate() 创建的堆内缓冲区和 ByteBuffer.allocateDirect() 创建的直接缓冲区,可以清晰地看到直接缓冲区在减少内存复制次数方面的优势。当使用 FileChannel 进行数据传输时,直接缓冲区可以直接与操作系统交互,而堆内缓冲区则需要额外的步骤将数据复制到直接缓冲区才能进行高效的 I/O 操作。

使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class BufferComparison { public static void main(String[] args) throws Exception { String src = "source.txt"; String dest = "dest.txt"; // 堆内缓冲区方式 long start = System.currentTimeMillis(); try (FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest)) { FileChannel inChannel = fis.getChannel(); FileChannel outChannel = fos.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(4096); while (inChannel.read(buffer) != -1) { buffer.flip(); outChannel.write(buffer); buffer.clear(); } } long heapTime = System.currentTimeMillis() - start; // 直接缓冲区方式 start = System.currentTimeMillis(); try (FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest)) { FileChannel inChannel = fis.getChannel(); FileChannel outChannel = fos.getChannel(); ByteBuffer directBuffer = ByteBuffer.allocateDirect(4096); while (inChannel.read(directBuffer) != -1) { directBuffer.flip(); outChannel.write(directBuffer); directBuffer.clear(); } } long directTime = System.currentTimeMillis() - start; System.out.println("Heap Time: " + heapTime + "ms"); System.out.println("Direct Time: " + directTime + "ms"); } }
直接缓冲区在零拷贝中的具体应用
直接缓冲区在零拷贝技术中的具体应用体现在 FileChannel.transferTo() 和 FileChannel.transferFrom() 方法上。这些方法允许数据直接在文件描述符和直接缓冲区之间传输,完全绕过了 JVM 的用户态内存。这意味着数据不需要从内核缓冲区复制到用户态的直接缓冲区,也不需要再从直接缓冲区复制到内核缓冲区用于发送。这种机制极大地减少了 CPU 的使用率和内存带宽的消耗,特别适用于大文件的传输和高性能网络服务器的开发。
import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.channels.FileChannel; public class ZeroCopyExample { public static void main(String[] args) throws Exception { String src = "source.txt"; String dest = "dest.txt"; try (FileInputStream fis = new FileInputStream(src); FileOutputStream fos = new FileOutputStream(dest)) { FileChannel inChannel = fis.getChannel(); FileChannel outChannel = fos.getChannel(); // 使用 transferTo 进行零拷贝传输 inChannel.transferTo(0, inChannel.size(), outChannel); } } }
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










