写点什么

Java 实现零拷贝

作者:极客罗杰
  • 2024-06-23
    上海
  • 本文字数:858 字

    阅读完需:约 3 分钟

Java实现零拷贝

百度百科对零拷贝是指计算机执行操作时,CPU 不需要先将数据从某处内存复制到另一个特定区域。这种技术通常用于通过网络传输文件时节省 CPU 周期和内存带宽。

Linux 官方的解释是:What is Zero Copy. “Zero”: Means that the number of times of copying data is 0. “Copy”: Means that the data is transferred from one storage to another storage area. So, if you put both “zero” and “copy” together, “zero copy” means that when the computer performs IO operations, the CPU does not need to copy data from one storage area to another, thereby reducing context switching and CPU copy time. It is an IO operation optimization technology.


// zerocopy uses transferTo()/transferFrompublic class ZeroCopyFile {    public void copyFile(File src, File dest) {        try(            FileChannel srcChannel = new FileInputStream(src).getChannel();            FileChannel destChannel = new FileOutputStream(dest).getChannel();        ) {            srcChannel.transferTo(0, srcChannel.size(), destChannel);           } catch(Exception e) {               System.out.println(e.getMessage());           }        return;    }
public void copyFile(String from, String to) throws IOException { long pos = 0; FileChannel fromFileChannel = null; FileChannel toFileChannel = null; try { fromFileChannel = new RandomAccessFile(from, "rw").getChannel(); toFileChannel = new RandomAccessFile(from, "rw").getChannel(); } catch(IOException ioException) { fromFileChannel.transferTo(pos, fromFileChannel.size(), toFileChannel); } finally { fromFileChannel.close(); toFileChannel.close(); } return; }}





复制代码


发布于: 刚刚阅读数: 4
用户头像

极客罗杰

关注

还未添加个人签名 2021-04-11 加入

还未添加个人简介

评论

发布
暂无评论
Java实现零拷贝_极客罗杰_InfoQ写作社区