Python 官方文档:入门教程 => 点击学习
定义 以上是书《深入理解java虚拟机》对直接内存的描述。直接缓冲区用的就是直接内存。 java NIO字节缓冲区要么是直接的,要么是非直接的。如果为直接字节缓冲区,则j
定义
以上是书《深入理解java虚拟机》对直接内存的描述。直接缓冲区用的就是直接内存。
基于NIO的本地IO直接内存使用:
传统IO对文件数据进行读写的流程:
流程说明(以上是应用程序完成一次文件拷贝的流程):
以上流程一共进行了四次上下文切换,四次数据拷贝。
使用mmap实现对传统文件IO优化。
mmap:通过把内核缓冲区和用户缓冲区映射在物理内存上映射为同一地址空间。这样就不用对数据进行复制了。
这个是传统的:
使用mmap后的IO大致流程:
数据拷贝次数从4次缩短到了两次。
相关api demo以及比较:详细api解释可以查看Java NIO学习篇之通道FileChannel详解
//使用直接缓冲区API进行一个700多M的文件进行拷贝
public static void testDirect(){
try {
long start = System.currentTimeMillis();
FileChannel srcFileChannel = FileChannel.open(Paths.get("C:\\Users\\Yehaocong\\Desktop\\test\\95462017-1-64.flv"), StandardOpenOption.READ);
FileChannel destFileChannel = FileChannel.open(Paths.get("C:\\Users\\Yehaocong\\Desktop\\test\\95462017-1-64-cp1.flv"),StandardOpenOption.CREATE,
StandardOpenOption.WRITE,StandardOpenOption.READ);
MappedByteBuffer srcByteBuffer = srcFileChannel.map(FileChannel.MapMode.READ_ONLY,0,srcFileChannel.size());
MappedByteBuffer descByteBuffer = destFileChannel.map(FileChannel.MapMode.READ_WRITE,0,srcFileChannel.size());
descByteBuffer.put(srcByteBuffer);
srcFileChannel.close();
destFileChannel.close();
System.out.println("直接缓冲区耗时:" + (System.currentTimeMillis()-start));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void testSimpleIO(){
try {
long start = System.currentTimeMillis();
FileChannel srcFileChannel = FileChannel.open(Paths.get("C:\\Users\\Yehaocong\\Desktop\\test\\95462017-1-64.flv"), StandardOpenOption.READ);
FileChannel destFileChannel = FileChannel.open(Paths.get("C:\\Users\\Yehaocong\\Desktop\\test\\95462017-1-64-cp.flv"),StandardOpenOption.CREATE,
StandardOpenOption.WRITE,StandardOpenOption.READ);
ByteBuffer byteBuffer = ByteBuffer.allocate((int) srcFileChannel.size());
while (srcFileChannel.read(byteBuffer)!=-1){
byteBuffer.flip();
destFileChannel.write(byteBuffer);
byteBuffer.clear();
}
srcFileChannel.close();
destFileChannel.close();
System.out.println("非缓冲区耗时:" + (System.currentTimeMillis()-start));
} catch (IOException e) {
e.printStackTrace();
}
}
执行结果:
到此这篇关于浅析Java NIO 直接缓冲区和非直接缓冲区的文章就介绍到这了,更多相关Java NIO 直接缓冲区和非直接缓冲区内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 浅析Java NIO 直接缓冲区和非直接缓冲区
本文链接: https://www.lsjlt.com/news/158766.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0