文件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. Spring 中的 JDBCTemplate

    新建一个java工程 写好spring配置文件,直接上代码 <?xml version="1.0" encoding="UTF-8"?> <b ...

  2. Animate.css动画库,简单的使用,以及源码剖析

    animate.css是什么?能做些什么? animate.css是一个css动画库,使用它可以很方便的快捷的实现,我们想要的动画效果,而省去了操作js的麻烦.同时呢,它也是一个开源的库,在GitHu ...

  3. 你有哪些相见恨晚的Chrome 扩展?

    「Chrome 没插件,香味少一半」,本期我们就来一起盘点一下chrome上那些相见恨晚的扩展. 1 JSONView2 Adblock Plus3 Keylines4 彩云小译5 单词发现者6 鼠标 ...

  4. 一起了解 .Net Foundation 项目 No.10

    .Net 基金会中包含有很多优秀的项目,今天就和笔者一起了解一下其中的一些优秀作品吧. 中文介绍 中文介绍内容翻译自英文介绍,主要采用意译.如与原文存在出入,请以原文为准. LLILC LLILC ( ...

  5. Samtec 5G探索之路

    序言:时代在发展,2020年5G作为元年.5G全程第五代移动通信技术(英语:5th generation mobile networks或5th generation wireless systems ...

  6. http协议、加密解密、web安全

    今天,就简单讲讲,我学习的知识.http协议:http协议是超文本传输协议,是用于传输超媒文档的应用层协议,同时,http协议是无状态协议,意味着,在服务器两个请求之间不会保留任何数据.虽然通常基于T ...

  7. node跨域方法

    第一种:jsonp 参看用nodejs实现json和jsonp服务 第二种:res.wirteHeadnode部分 var http = require('http') var url = requi ...

  8. 手机浏览器自动播放视频video(设置autoplay无效)的解决方案

    1.问题的提出 某一天接了个需求,需要在手机的H5页面内加入视频,我开开心心做完,准备交付的时候,问题来了,PM想要用户一进入页面,视频就开始播放,不需要用户手动点击. 2.尝试解决 加autopla ...

  9. 关于CSS设置页面背景图的一些疑问

    关于背景图片的位置其background-position设置背景图片的位置有两种方式,一种是是根据像素设置,第二种根据百分比设置,第一种根据像素的位置是很简单的,只是关于百分比这个设置理解特别容易出 ...

  10. Kafka体系架构详细分解

    我的个人博客排版更舒服: https://www.luozhiyun.com/archives/260 基本概念 Kafka 体系架构 Kafka 体系架构包括若干 Producer.若干 Broke ...