Java WeakReference类

279 阅读2分钟

What's WeakReference class?

WeakReference 是Java中的一个类,它是弱引用的一种实现。 弱引用是一种相对较弱的引用,它允许对象被垃圾回收器回收,即使该对象还有弱引用指向它。

在Java中,当一个对象只被弱引用引用时,如果垃圾回收器进行垃圾回收时发现该对象只有弱引用指向它,那么这个对象就会被回收。 弱引用通常用于解决内存泄漏问题或实现一些特定的功能,如 ThreadLocal 中的Entry 对象就使用了 WeakReference 来持有ThreadLocal 对象的弱引用。

WeakReference 类的常用方法

  • get():获取弱引用引用的对象,如果对象还未被回收,则返回对象,否则返回null。
  • clear():清除弱引用,使其不再引用任何对象。
  • isEnqueued():判断弱引用引用的对象是否已经被垃圾回收器标记为即将回收。

通过使用WeakReference ,可以避免一些对象持续占用内存而无法被及时回收的问题,从而提高程序的内存利用率和性能。

For example

import java.lang.ref.WeakReference;
public class WeakReferenceExample {
    public static void main(String[] args) {
        // 创建一个字符串对象
        String str = new String("Hello World");
        // 创建一个弱引用
        WeakReference<String> weakRef = new WeakReference<>(str);
        System.out.println("Before nulling the reference: " + weakRef.get());
        str = null;   // 将原始引用置为null
        System.gc(); // 手动触发垃圾回收
        System.out.println("After nulling the reference: " + weakRef.get());
    }
    /*
     * Output:
     * Before nulling the reference: Hello World
     * After nulling the reference: null
     *///~
}

在上面的示例中,我们首先创建一个字符串对象 str,然后使用 WeakReference 创建了一个弱引用weakRef 指向该字符串对象。在将原始引用 str 置为null后,手动触发了垃圾回收。在输出中,我们可以看到在将原始引用置为null后,通过弱引用 weakRef 获取到的对象为null,说明对象已经被成功回收。