文件copy是java的io部分不可忽视的内容。

我是李福春,我在准备面试,今天的问题是:

zero-copy是怎么回事?

操作系统的空间划分为内核态空间, 用户态空间;

内核态空间相对操作系统具备更高的权限和优先级;

用户态空间即普通用户所处空间。

zero-copy指的使用类似java.nio的transforTo方法进行文件copy,文件的copy直接从磁盘到内核态空间,不经过用户态空间,再写到磁盘,减少了io的消耗,避免了不必要的copy 和上下文切换,所以比较高效。

接下来对面试官可能扩展的问题进行一些拓展:

java的文件copy方式

java.io流式copy

package org.example.mianshi.filecopy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files; /**
* 说明:传统的文件copy
* @author carter
* 创建时间: 2020年03月26日 9:32 上午
**/ public class JioFileCopyApp { public static void main(String[] args) { final File d = new File("/data/appenvs/denv.properties");
final File s = new File("/data/appenvs/env.properties"); System.out.println("source file content :" + s.exists());
System.out.println("target file content :" + d.exists()); System.out.println("source content:");
try {
Files.lines(s.toPath()).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
} System.out.println("do file copy !"); copy(s, d); System.out.println("target file content :" + d.exists());
System.out.println("target content:");
try {
Files.lines(d.toPath()).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
} } private static void copy(File s, File d) { try (
final FileInputStream fileInputStream = new FileInputStream(s); final FileOutputStream fileOutputStream = new FileOutputStream(d)
) { byte[] buffer = new byte[1024];
int length;
while ((length = fileInputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, length);
} } catch (IOException e) {
e.printStackTrace();
} } }

代码可以运行;copy流程如下图:它不是zero-copy的,需要切换用户态空间和内核态空间,路径比较长,io消耗和上线文切换的消耗比较明显,这是比较低效的copy.

java.nioChannel式copy

package org.example.mianshi.filecopy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.nio.file.Files; /**
* 说明:传统的文件copy
* @author carter
* 创建时间: 2020年03月26日 9:32 上午
**/ public class JnioFileCopyApp { public static void main(String[] args) { final File d = new File("/data/appenvs/ndenv.properties");
final File s = new File("/data/appenvs/env.properties"); System.out.println(s.getAbsolutePath() + "source file content :" + s.exists());
System.out.println(d.getAbsolutePath() +"target file content :" + d.exists()); System.out.println("source content:");
try {
Files.lines(s.toPath()).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
} System.out.println("do file copy !"); copy(s, d); System.out.println(d.getAbsolutePath() +"target file content :" + d.exists());
System.out.println("target content:");
try {
Files.lines(d.toPath()).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
} } private static void copy(File s, File d) { try (
final FileChannel sourceFileChannel = new FileInputStream(s).getChannel(); final FileChannel targetFileChannel = new FileOutputStream(d).getChannel()
) { for (long count= sourceFileChannel.size();count>0;){ final long transferTo = sourceFileChannel.transferTo(sourceFileChannel.position(), count, targetFileChannel); count-=transferTo; } } catch (IOException e) {
e.printStackTrace();
} } }

copy过程如下图:明显,不用经过用户态空间,是zero-copy,减少了io的消耗以及上下文切换,比较高效。

Files工具类copy

package org.example.mianshi.filecopy;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption; /**
* 说明:Files的文件copy
* @author carter
* 创建时间: 2020年03月26日 9:32 上午
**/ public class FilesFileCopyApp { public static void main(String[] args) { final File d = new File("/data/appenvs/fenv.properties");
final File s = new File("/data/appenvs/env.properties"); System.out.println("source file content :" + s.exists());
System.out.println("target file content :" + d.exists()); System.out.println("source content:");
try {
Files.lines(s.toPath()).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
} System.out.println("do file copy !"); copy(s, d); System.out.println("target file content :" + d.exists());
System.out.println("target content:");
try {
Files.lines(d.toPath()).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
} } private static void copy(File s, File d) { try {
Files.copy(s.toPath(),d.toPath(), StandardCopyOption.COPY_ATTRIBUTES);
} catch (IOException e) {
e.printStackTrace();
} } }

面试官一般喜欢刨根问底,那么来吧!贴一下源码:

 public static Path copy(Path source, Path target, CopyOption... options)
throws IOException
{
FileSystemProvider provider = provider(source);
if (provider(target) == provider) {
// same provider
provider.copy(source, target, options);
} else {
// different providers
CopyMoveHelper.copyToForeignTarget(source, target, options);
}
return target;
}

底层通过SPI,即ServiceLoader的方式加载不同文件系统的本地处理代码。

分类如下:

我们使用最多的UnixFsProvider,实际上是 直接从 用户态空间copy到用户态空间,使用了本地方法内联加持优化,但是它不是zero-copy, 性能也不会太差。

如何提高io的效率

1, 使用缓存,减少io的操作次数;


2,使用zero-copy,即类似 java.nio的 transferTo方法进行copy;


3, 减少传输过程中不必要的转换,比如编解码,最好直接二进制传输;

buffer

buffer的类层级图如下:

除了bool其他7个原生类型都有对应的Buffer;

面试官如果问细节,先说4个属性, capacity, limit ,position, mark

再描述byteBuffer的读写流程。

然后是DirectBuffer,这个是直接操作堆外内存,比较高效。但是用好比较困难,除非是流媒体的行业,不会问的这么细,直接翻源码好好准备,问一般也是技术专家来问你了。

小结

本篇回答了什么是zero-copy,然后介绍了java体系实现文件copy的3中方式,(扩展的第三方库不算在内);


然后简要介绍了如何提高io效率的三种方法,以及提高内存利用率的Buffer做了系统级的介绍。


不啰嗦,可以快速通过下图条理化本篇内容,希望对你有所帮助。

原创不易,转载请注明出处。

面试刷题12:zero copy是怎么回事?的更多相关文章

  1. 安利一个基于Spring Cloud 的面试刷题系统。面试、毕设、项目经验一网打尽

    推荐: 接近100K star 的Java学习/面试指南 Github 95k+点赞的Java面试/学习手册.pdf 今天给小伙伴们推荐一个朋友开源的面试刷题系统. 这篇文章我会从系统架构设计层面详解 ...

  2. 回文的范围——算法面试刷题2(for google),考察前缀和

    如果一个正整数的十进制表示(没有前导零)是一个回文字符串(一个前后读取相同的字符串),那么它就是回文.例如,数字5, 77, 363, 4884, 11111, 12121和349943都是回文. 如 ...

  3. AI面试刷题版

    (1)代码题(leetcode类型),主要考察数据结构和基础算法,以及代码基本功 虽然这部分跟机器学习,深度学习关系不大,但也是面试的重中之重.基本每家公司的面试都问了大量的算法题和代码题,即使是商汤 ...

  4. 有效的括号序列——算法面试刷题4(for google),考察stack

    给定一个字符串所表示的括号序列,包含以下字符: '(', ')', '{', '}', '[' and ']', 判定是否是有效的括号序列. 括号必须依照 "()" 顺序表示, & ...

  5. 相似的RGB颜色——算法面试刷题3(for google),考察二分

    在本题中,每个大写字母代表从“0”到“f”的一些十六进制数字. 红绿蓝三元色#AABBCC可以简写为#ABC. 例如,#15c是颜色#1155cc的简写. 现在,假设两种颜色#ABCDEF和#UVWX ...

  6. 有效单词词广场——算法面试刷题5(for google),考察数学

    给定一个单词序列,检查它是否构成一个有效单词广场.一个有效的单词广场应满足以下条件:对于满足0≤k<max(numRows numColumns)的k,第k行和第k列对应的字符串应该相同,. 给 ...

  7. 面试刷题31:分布式ID设计方案

    面试中关于分布式的问题很多.(分布式事务,基本理论CAP,BASE,分布式锁)先来一个简单的. 简单说一下分布式ID的设计方案? 首先要明确在分布式环境下,分布式id的基本要求. 1, 全局唯一,在分 ...

  8. 面试刷题11:java系统中io的分类有哪些?

    随着分布式技术的普及和海量数据的增长,io的能力越来越重要,java提供的io模块提供了足够的扩展性来适应. 我是李福春,我在准备面试,今天的问题是: java中的io有哪几种? java中的io分3 ...

  9. 面试刷题17:线程两次start()会发生什么?

    线程是并发编程的基础元素,是系统调度的最小单元,现代的jvm直接对应了内核线程.为了降低并发编程的门槛,go语言引入了协程. 你好,我是李福春,我在准备面试,今天的题目是? 一个线程两次调用start ...

随机推荐

  1. Chrome 调试 react-native 通过Network面板查看网络请求

    参考 https://github.com/facebook/react-native/issues/934 三楼 真机或模拟器下 Debug JS Remotely, 会打开chrome,地址为ip ...

  2. Python字符串编码——Unicode

    ASCII码 我们知道,在计算机内部,所有的信息最终都表示为一个二进制的字符串.每一个二进制位(bit)有0和1两种状态,因此八个二进制位就可以组合出256种状态,这被称为一个字节(byte).也就是 ...

  3. A Knight's Journey (DFS)

    题目: Background The knight is getting bored of seeing the same black and white squares again and agai ...

  4. AndroidImageSlider

    最核心的类是SliderLayout,他继承自相对布局,包含了可以左右滑动的SliderView,以及页面指示器PagerIndicator.这两部分都可以自定义. AndroidImageSlide ...

  5. springboot利用swagger构建api文档

    前言 Swagger 是一款RESTFUL接口的文档在线自动生成+功能测试功能软件.本文简单介绍了在项目中集成swagger的方法和一些常见问题.如果想深入分析项目源码,了解更多内容,见参考资料. S ...

  6. Python爬虫开发教程

     正文   现在Python语言大火,在网络爬虫.人工智能.大数据等领域都有很好的应用.今天我向大家介绍一下Python爬虫的一些知识和常用类库的用法,希望能对大家有所帮助.其实爬虫这个概念很简单,基 ...

  7. TOMCAT封装DBCP

    ## 数据源 ## #Tomcat封装的DBCP: >> 基本知识: tomcat在默认情况下已经集成了DBCP: >> JNDI: |-- 基本概念: 在tomcat启动的时 ...

  8. Android Base64图片无法长按保存 问题解决

    踩了一个巨坑. 目前微信ios/android 均能长按保存src=base64的图片  (微信android x5 专门解决了这个问题); 但是android其他App没有针对解决这个系统问题(姑且 ...

  9. Yuchuan_Linux_C 编程之十 进程及进程控制

    一.整体大纲 二.基础知识 1. 进程相关概念 1)程序和进程 程序,是指编译好的二进制文件,在磁盘上,不占用系统资源(cpu.内存.打开的文件.设备.锁....)     进程,是一个抽象的概念,与 ...

  10. JetBrains全系列产品2019.3.2注解教程

    1.JetBrains官方网站 https://www.jetbrains.com/ JetBrains是一家捷克的软件开发公司 IDE工具: * IntelliJ IDEA    一套智慧型的Jav ...