Java弱引用WeakReference的理解与使用
2023-10-18 本文已影响0人
电动自行车租赁
Java弱引用WeakReference的理解与使用
WeakReference是弱引用,弱引用持有的对象实例是可以被垃圾回收器回收的。通常用于保存保存对象的引用,却又不会影响对象被GC回收。对于DEBUG和内存监视工具非常有用。一般也常与队列联合使用。下面简单的介绍下如何使用WeakReference
import java.lang.ref.WeakReference;
public class TestWeakReferece {
public static void main(String[] args) {
Object o = new Object();
WeakReference<Object> weak = new WeakReference<Object>(o);
o = null;
int i = 0;
while (weak.get() != null) {
i++;
System.out.println("Object is not null. count is " + i);
if (i % 10 == 0) {
System.gc();
System.out.println("System.gc() was called!");
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
System.out.println("object o was cleared by JVM!");
}
}
测试结果
Object is not null. count is 1
Object is not null. count is 2
Object is not null. count is 3
Object is not null. count is 4
Object is not null. count is 5
Object is not null. count is 6
Object is not null. count is 7
Object is not null. count is 8
Object is not null. count is 9
Object is not null. count is 10
System.gc() was called!
object o was cleared by JVM!
WeakReference的语法:
WeakReference<T> weakReference = new WeakReference<T>(referent);
当要获得weak reference引用的对象时, 首先需要判断它是否已经被回收:
weakReference.get();
如果此方法为空, 那么说明weakReference指向的对象已经被回收了。
小结:
1.Java中当一个对象仅被一个弱引用引用时,如果GC运行, 那么这个对象就会被回收。
2.弱引用的一个特点是它何时被回收是不可确定的;