弱引用WeakReference

概述

当一个对象仅仅被弱引用指向,而没有任何强引用指向的时候,该对象只能生存到下一次垃圾收集发生之前。当垃圾收集器工作时,不论当前的内存空间是否足够,该对象都会被回收。

使用
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 {
    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
参考

https://www.jianshu.com/p/964fbc30151a

你可能感兴趣的:(弱引用WeakReference)