1、代码取消强引用后,gc回收对象
java
public static void main(String[] args) {
Object obj = new Object();
WeakReference<Object> weakRef = new WeakReference<>(obj);
System.out.println(weakRef.get());
obj = null; // 取消强引用,后续gc会被回收,如果不设为null取消强引用,gc也无法回收
System.gc(); // 提示垃圾回收器进行回收
System.out.println(weakRef.get());
// 判断对象是否被回收
if (weakRef.get() == null) {
System.out.println("对象已经被回收");
} else {
System.out.println("对象仍然存在");
}
}
2、不取消强引用,gc无法回收
java
public static void main(String[] args) {
Object obj = new Object();
WeakReference<Object> weakRef = new WeakReference<>(obj);
System.out.println(weakRef.get());
System.gc(); // 提示垃圾回收器进行回收
System.out.println(weakRef.get());
// 判断对象是否被回收
if (weakRef.get() == null) {
System.out.println("对象已经被回收");
} else {
System.out.println("对象仍然存在");
}
}