概述:
1.直接內存不是虛擬運行時數據區的一部分,也不是《java虛擬機規范》中定義的內存直接區域。
2.直接內存是java堆外的,直接向系統申請的內存區間。
3.來源於NIO,通過存在堆中的DirectByteBuffer操作Native內存。
4.通常,訪問直接內存的速度會優於java堆。即讀寫性能高。
出於性能考慮,讀寫頻繁的場合可能會考慮使用直接內存。
java的NIO庫允許java程序使用直接內存
5.直接內存也會導致oom異常
6.由於直接內存在java堆外,因此他的大小不會受限於-Xmx指定的最大堆大小,但系統內存是有限的,java堆和直接內存的總和依然受限於操作系統能給出的最大內存
直接內存的缺點:
分配/回收成本較高
7.不受jvm內存回收管理
8.直接內存大小可以通過MaxDirectMemorySize設置
9.如果不指定,默認與堆的最大值-Xmx參數值一致
public class BufferTest { private static final String TO = "F:\\test\\1.5gtest.mp4"; private static final int _100Mb = 1024 * 1024 * 100; public static void main(String[] args) { long sum = 0; String src = "F:\\test\\1.5gtest.mp4"; for (int i = 0; i < 3; i++) { String dest = "F:\\test\\1.5gtest_" + i + ".mp4"; // sum += io(src,dest);//54606 sum += directBuffer(src,dest);//50244 } System.out.println("總花費的時間為:" + sum ); } private static long directBuffer(String src,String dest) { long start = System.currentTimeMillis(); FileChannel inChannel = null; FileChannel outChannel = null; try { inChannel = new FileInputStream(src).getChannel(); outChannel = new FileOutputStream(dest).getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocateDirect(_100Mb); while (inChannel.read(byteBuffer) != -1) { byteBuffer.flip();//修改為讀數據模式 outChannel.write(byteBuffer); byteBuffer.clear();//清空 } } catch (IOException e) { e.printStackTrace(); } finally { if (inChannel != null) { try { inChannel.close(); } catch (IOException e) { e.printStackTrace(); } } if (outChannel != null) { try { outChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } long end = System.currentTimeMillis(); return end - start; } private static long io(String src,String dest) { long start = System.currentTimeMillis(); FileInputStream fis = null; FileOutputStream 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 (IOException e) { e.printStackTrace(); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } long end = System.currentTimeMillis(); return end - start; } }