I0-零拷贝

零拷贝的“零”是指用户态和内核态间copy数据的次数为零,netty采用的零拷贝

传统的数据copy(文件到文件、client到server等)涉及到四次用户态内核态切换、四次copy。四次copy中,两次在用户态和内核态间copy需要CPU参与、两次在内核态与IO设备间copy为DMA方式不需要CPU参与。零拷贝避免了用户态和内核态间的copy、减少了两次用户态内核态间的切换。

零拷贝可以提高数据传输效率,但对于需要在用户传输过程中对数据进行加工的场景(如加密)就不适合使用零拷贝。

传统IO

读取文件 文件-系统内核缓冲区-系统内存缓冲区  写文件 系统内存缓冲区-内核缓冲区-写入磁盘

 

零拷贝

文件-内核缓冲区   内核缓冲区-磁盘

 

 

Java NIO 零拷贝示例

 

 

/**
* 零拷贝文件
* Created by wuliangfeng on 2021/4/23.
*/
public class ZerocopyFile {
public static void main(String[] args){
try{
String fromPath="D:\\json.txt";
String toPath="E:\\json.txt";
//copyToFile(fromPath,toPath);
// copyFormFile(fromPath,toPath);
copyZoreFile(fromPath,toPath);
}catch(Exception e){
e.printStackTrace();
}
}
private static void copyZoreFile(String fromPath, String toPath) throws IOException {
FileChannel fromChannel=FileChannel.open(Paths.get(fromPath), StandardOpenOption.READ);
FileChannel toChannel=FileChannel.open(Paths.get(toPath),StandardOpenOption.CREATE,StandardOpenOption.READ,StandardOpenOption.WRITE);
MappedByteBuffer formMappedByteBuffer=fromChannel.map(FileChannel.MapMode.READ_ONLY,0,fromChannel.size());
MappedByteBuffer toMappedByteBuffer=toChannel.map(FileChannel.MapMode.READ_WRITE,0,fromChannel.size());
byte[] bytes=new byte[formMappedByteBuffer.limit()];
formMappedByteBuffer.get(bytes);
toMappedByteBuffer.put(bytes);
fromChannel.close();
toChannel.close();;
}
private static void copyToFile(String fromPath, String toPath) throws IOException {
//rw readWrite
FileChannel fromChannel=new RandomAccessFile(fromPath,"rw").getChannel();
FileChannel toChannel=new RandomAccessFile(toPath,"rw").getChannel();
fromChannel.transferTo(0,fromChannel.size(),toChannel);
fromChannel.close();
toChannel.close();
}
private static void copyFormFile(String fromPath, String toPath)throws IOException{
FileChannel fromChannel=new FileInputStream(fromPath).getChannel();
FileChannel toChannel=new FileOutputStream(toPath).getChannel();
toChannel.transferFrom(fromChannel,0,fromChannel.size());
fromChannel.close();
toChannel.close();
}
}
posted @ 2021-04-23 17:29  陈旭元_alun  阅读(162)  评论(0编辑  收藏  举报