垃圾判断算法

垃圾判断算法

引用计算法
  1. 概念:给对象添加一个引用计算器,每当有一个地方引用它时,计算器就加1;当引用失效时,计算器值就减1;当计数器值为0时视为失效。
  2. 缺陷:很难解决对象之间的相互循环引用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class ReferenceCountingGC {

public Object instance = null;

private static final int _1MB = 1024 * 1024;

private byte[] bigSize = new byte[2 * _1MB];

public void test() {

ReferenceCountingGC referenceCountingGC_A = new ReferenceCountingGC();
ReferenceCountingGC referenceCountingGC_B = new ReferenceCountingGC();

referenceCountingGC_A.instance = referenceCountingGC_B;
referenceCountingGC_B.instance = referenceCountingGC_A;

referenceCountingGC_A = null;
referenceCountingGC_B = null;

System.gc();
}

public static void main(String[] args) {
ReferenceCountingGC referenceCountingGC = new ReferenceCountingGC();
referenceCountingGC.test();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
CommandLine flags: -XX:InitialHeapSize=134217728 -XX:MaxHeapSize=2147483648 -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseParallelGC 
0.269: [GC (System.gc()) [PSYoungGen: 9519K->2880K(38400K)] 9519K->2888K(125952K), 0.0028893 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
0.272: [Full GC (System.gc()) [PSYoungGen: 2880K->0K(38400K)] [ParOldGen: 8K->2766K(87552K)] 2888K->2766K(125952K), [Metaspace: 3310K->3310K(1056768K)], 0.0043064 secs] [Times: user=0.01 sys=0.00, real=0.01 secs]
Heap
PSYoungGen total 38400K, used 333K [0x0000000795580000, 0x0000000798000000, 0x00000007c0000000)
eden space 33280K, 1% used [0x0000000795580000,0x00000007955d34a8,0x0000000797600000)
from space 5120K, 0% used [0x0000000797600000,0x0000000797600000,0x0000000797b00000)
to space 5120K, 0% used [0x0000000797b00000,0x0000000797b00000,0x0000000798000000)
ParOldGen total 87552K, used 2766K [0x0000000740000000, 0x0000000745580000, 0x0000000795580000)
object space 87552K, 3% used [0x0000000740000000,0x00000007402b3890,0x0000000745580000)
Metaspace used 3318K, capacity 4496K, committed 4864K, reserved 1056768K
class space used 365K, capacity 388K, committed 512K, reserved 1048576K

从GC日志看,对象由PSYoungGen转移至ParOldGen中。

根搜索算法
  1. 概念:通过一系列名为GC Roots的对象作为起始点,从这些节点开始向下搜索,搜索所走过的路径称为引用链,当一个对象到GC Roots没有任何引用链相连时,则此对象视为不可用。
  2. 可被视为GC Roots的对象
    • 虚拟机栈(栈帧中的本地变量表)中引用的对象
    • 方法区中的类静态属性引用的对象
    • 方法区中的常量引用的对象
    • 本地方法栈中Native方法引用的对象

引用分级

  • 强引用(Strong Reference):永远不会回收
  • 软引用(Soft Reference):在内存溢出前回收
  • 弱引用(Weak Reference):垃圾收集时回收
  • 虚引用(Phantom Reference):无影响,用于系统通知