概述
当一个对象仅仅被弱引用
指向,而没有任何强引用
指向的时候,该对象只能生存到下一次垃圾收集发生之前。当垃圾收集器工作时,不论当前的内存空间是否足够,该对象都会被回收。
使用
public class Person {
String name;
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
// gc 在回收对象之前调用该方法
@Override
protected void finalize() throws Throwable {
System.out.println("finalize...");
super.finalize();
}
}
import java.lang.ref.WeakReference;
public class WeakPerson extends WeakReference<Person> {
public WeakPerson(Person person) {
super(person);
}
}
1. 对象同时存在强引用和弱引用时,发生gc,不会回收对象
public class WeakReferenceTest {
public static void main(String[] args) {
// person 强引用,weakPerson 弱引用
Person person = new Person("Lisa");
WeakPerson weakperson = new WeakPerson(person);
System.out.println(weakperson.get());
System.gc();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(weakperson.get());
}
}
输出结果如下
Lisa
Lisa
2. 对象仅存在弱引用时,发生gc,会回收对象
public class WeakReferenceTest {
public static void main(String[] args) {
Person person = new Person("Lisa");
WeakPerson weakperson = new WeakPerson(person);
person = null;
System.out.println(weakperson.get());
System.gc();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(weakperson.get());
}
}
输出结果如下
Lisa
finalize...
null