定义
以上是书《深入理解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 直接缓冲区和非直接缓冲区内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!