1.不是虚拟机运行时数据区的一部分,也不是Java虚拟机定义的内存区域 2.直接内存是在Java堆外的、直接向系统申请的内存空间。 ByteBuffer.allocateDirect(); 3.来源NIO,通过存在堆中的DirectByteBuffer操作Native内存 4.通常,访问直接内存的速度会优于Java堆。即读写性能高。 因此出于性能考虑,读写频繁的场合可能会考虑使用直接内存 Java的NIO库允许Java程序使用直接内存,用于数据缓冲区 5.直接内存的OOM设置:Direct buffer memory:OutofMemory 通过MaxDirectMemorySize设置 如果不指定,默认与堆的最大值-Xmx参数一致 6.缺点:分配回收成本较高;不受JVM内存回收管理
public static test{ private static final int _100mb = 1024*1024*1024; public static void main(String[] args){ long sum = 0; String src = "D:\\test\\花木兰.mp4"; for(int i =0;i<3;i++){ String dest = "D:\\test\\花木兰"+i+".mp4"; sum+=io(src,dest); //sum += directBuffer(src,dest); } System.out.println("总花费的时间:" + sum); } private static long directBuffer(String src ,String dest){ long start = System.currentTimeMills(); FileChannel inChannel = null; FileChannel outChannel = null; try{ inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dest).getChannel(); ByreBuffer byteBuffer = ByteBuffer.allocateDirect(_100Mb); while(inChannel.read(byteBuffer) != -1){ byteBuffer.flip();//修改为读取数据模式 outChannel.write(byteBuffer); byteBuffer.clear();//清空 } } catch(IOException e){ e.oru=intStackTrace(); } finally { //关闭流 } } private static long io(String src, String dest){ long start = System.currentTimeMills(); FileChannel fis = null; FileChannel fos = null; try{ fis = new FileInputStream(src); fos = new FileOutPutStream(dest); byte[] buffer = new byte[_100Mb]; while(true){ int len = fis.read(buffer); if(len == -1){ break; } fos.write(buffer,0,len); } }catch(){}finallly{} } }