今天在研究JVM的直接内存溢出时发现直接内存和堆内存同样,在直接内存快满时会触发full gc,full gc会将未被引用的对象及其指向的直接内存释放掉,以下为测试代码:java
package test.oom; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; /** * VM args: -XX:+PrintGCDetails -XX:MaxDirectMemorySize=500M * @author TZ0643 * */ public class DirectMemoryOOM { private static final int _1MB = 1024 * 1024 * 300; public static void main(String[] args) throws Exception { int count = 0; List<ByteBuffer> bufs = new ArrayList<ByteBuffer>(); while(true) { count++; System.out.println("count=" + count); Thread.sleep(10000); System.out.println("allocate direct."); ByteBuffer buf = ByteBuffer.allocateDirect(_1MB); // 将引用加入集合中防止被GC回收致使直接内存被释放 // bufs.add(buf); } } }
以下为执行日志:测试
count=1 spa
allocate direct.
count=2
allocate direct.
[GC [PSYoungGen: 655K->536K(18944K)] 655K->536K(61440K), 0.0046150 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
[Full GC [PSYoungGen: 536K->0K(18944K)] [ParOldGen: 0K->479K(42496K)] 536K->479K(61440K) [PSPermGen: 2548K->2547K(21504K)], 0.0184197 secs] [Times: user=0.05 sys=0.00, real=0.02 secs]
Exception in thread "main" Heap
java.lang.OutOfMemoryError: Direct buffer memory
at java.nio.Bits.reserveMemory(Bits.java:658)
at java.nio.DirectByteBuffer.<init>(DirectByteBuffer.java:123)
at java.nio.ByteBuffer.allocateDirect(ByteBuffer.java:306)
at test.oom.DirectMemoryOOM.main(DirectMemoryOOM.java:27)
PSYoungGen total 18944K, used 983K [0x00000000eb280000, 0x00000000ec780000, 0x0000000100000000)
eden space 16384K, 6% used [0x00000000eb280000,0x00000000eb375d18,0x00000000ec280000)
当程序在执行第一次的时候内存为300多M,当buf不添加到list集合中时,不会出现OOM,JVM每次都释放直接内存;日志
当buf添加到list中,则出现OOM,因为buf被引用,没法被full gc回收,致使直接内存为600M,而最大直接内存为500M,出现OOMcode