引用计数法
存在问题

可达性分析算法
/**
* 1.运行程序
* 2.jps 查看运行中的进程id
* 3.jmap -dump:format=b,live,file=1.bin 27300 转储内存信息
*/
public static void main(String[] args) throws IOException {
List<Object> list=new ArrayList<>();
list.add("1");
list.add("2");
System.out.println("回收前");
System.in.read();
list=null;
System.out.println("回收后");
System.in.read();
System.out.println("end...");
}
转储内存信息

分析:回收前

分析:回收后


/**
* 软引用(SoftReference)
* -Xmx20m -XX:+PrintGCDetails -verbose:gc
*/
public class SoftReferenceTest {
private static final int _4M=1024*1024*4;
public static void main(String[] args) {
//GC_Root
List<SoftReference<byte[]>> list=new ArrayList<>();
//关联引用队列:当对象被回收时加入队列
ReferenceQueue<byte[]> queue=new ReferenceQueue<>();
//1.添加5个软引用
for (int i = 0; i < 5; i++) {
SoftReference<byte[]> ref=new SoftReference<>(new byte[_4M],queue);
System.out.print(ref.get());
list.add(ref);
System.out.println(" "+list.size());
}
//2.判断5个软引用是否被回收了对象,是的话移除软引用
Reference<? extends byte[]> poll = queue.poll();
while(poll!=null){
list.remove(poll);
poll=queue.poll();
}
//3.输出当前list中的所有引用
System.out.println("========================");
for (SoftReference<byte[]> item: list) {
System.out.println(item.get());
}
}
}

/**
* 弱引用
* -Xmx20m -XX:+PrintGCDetails -verbose:gc
*/
public class WeakReferenceTest {
private static final int _4M=1024*1024*4;
public static void main(String[] args) {
//GC_Root
List<WeakReference<byte[]>> list=new ArrayList<>();
//1.添加5个弱引用
for (int i = 0; i < 6; i++) {
WeakReference<byte[]> ref=new WeakReference<>(new byte[_4M]);
list.add(ref);
System.out.print("第"+(i+1)+"次:");
for (WeakReference<byte[]> item: list) {
System.out.print(item.get()+" ");
}
System.out.println();
}
System.out.println("========================");
}
}

