看一段程序
package day20200314;
import java.lang.ref.SoftReference;
/**
* @Author: xiaoshijiu
* @Date: 2020/3/14
* @Description: 分析GC打印的日志具体内容
*/
public class GCDetailsAnalyze {
public static void main(String[] args) {
SoftReference<byte[]> softReference = new SoftReference<>(new byte[5 * 1024 * 1024]);
System.gc();
byte[] bytes = new byte[6 * 1024 * 1024];
}
}
设置了JVM参数:
-Xmx10m -Xms10m -XX:+PrintGCDetails
最大堆内存10m、初始化堆内存10m、开启了GC日志输出
首先都很清楚,软引用的特点:
内存不足的时候,会被垃圾回收,内存足够,不会被回收;
运行结果:
"C:\Program Files\Java\jdk1.8.0_111\bin\java.exe" -Xmx10m -Xms10m -XX:+PrintGCDetails...
[GC (System.gc()) [PSYoungGen: 2025K->488K(2560K)] 7145K->5824K(9728K), 0.0012223 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
[Full GC (System.gc()) [PSYoungGen: 488K->0K(2560K)] [ParOldGen: 5336K->5792K(7168K)] 5824K->5792K(9728K), [Metaspace: 3479K->3479K(1056768K)], 0.0073629 secs] [Times: user=0.00 sys=0.00, real=0.01 secs]
[GC (Allocation Failure) [PSYoungGen: 0K->0K(2560K)] 5792K->5792K(9728K), 0.0003410 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
[GC (Allocation Failure) [PSYoungGen: 0K->0K(2560K)] 5792K->5792K(9728K), 0.0004555 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
[Full GC (Allocation Failure) [PSYoungGen: 0K->0K(2560K)] [ParOldGen: 5792K->5792K(7168K)] 5792K->5792K(9728K), [Metaspace: 3479K->3479K(1056768K)], 0.0032795 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
[GC (Allocation Failure) [PSYoungGen: 0K->0K(2560K)] 5792K->5792K(9728K), 0.0004670 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
[Full GC (Allocation Failure) [PSYoungGen: 0K->0K(2560K)] [ParOldGen: 5792K->653K(7168K)] 5792K->653K(9728K), [Metaspace: 3479K->3479K(1056768K)], 0.0094774 secs] [Times: user=0.03 sys=0.00, real=0.01 secs]
// 下面是堆内存总的概况,各区域所占大小,以及被使用情况
Heap
PSYoungGen total 2560K, used 20K [0x00000000ffd00000, 0x0000000100000000, 0x0000000100000000)
eden space 2048K, 1% used [0x00000000ffd00000,0x00000000ffd05360,0x00000000fff00000)
from space 512K, 0% used [0x00000000fff80000,0x00000000fff80000,0x0000000100000000)
to space 512K, 0% used [0x00000000fff00000,0x00000000fff00000,0x00000000fff80000)
ParOldGen total 7168K, used 6797K [0x00000000ff600000, 0x00000000ffd00000, 0x00000000ffd00000)
object space 7168K, 94% used [0x00000000ff600000,0x00000000ffca3750,0x00000000ffd00000)
Metaspace used 3486K, capacity 4498K, committed 4864K, reserved 1056768K
class space used 387K, capacity 390K, committed 512K, reserved 1048576K
Process finished with exit code 0
总结的一张图:
Full GC:对整个堆内存空间的一次垃圾回收
GC:对年轻代空间的一次垃圾回收
Allocation Failure:“分配失败”,即为新对象分派内存不够
System.gc():执行该方法触发的GC
程序分析:
首先软引用指向的对象5m,主动进行GC,这里的5m对象不会被回收;
可以看出来GC( System.gc() )日志, [ParOldGen: 5336K->5792K(7168K)]
5m对象在老年代中,也并没有被回收;
再创建一个6m对象,内存不够,JVM进行GC清理垃圾,会回收上面的5m对象;
可以看出来Full GC( Allocation Failure )日志,[ParOldGen: 5792K->653K(7168K)]
5m对象在老年代中被回收了;