强引用>软引用>弱引用>虚引用
强引用(Strong Reference)
它是最普遍的引用,比如Object obj = new Object(),即使抛出OutOfMemoryError终止程序也不会回收具有强引用的对象,但是通过将对象设置为null来弱化引用,使其被回收
String str = new String("abc"); //强引用
软引用(Soft Reference)
对象处于有用但非必须的状态,只有当内存空间不足时,GC会回收该引用的对象的内存,因此它可以用来实现高速缓存
SoftReference<Stirng> softRef = new SoftReference<String>(str); //软引用
弱引用(Weak Reference)
非必须的对象,比软引用更弱一点,GC时被回收。但是被回收的概率也不大,因为GC线程优先级比较低,适用于引用偶尔被使用且不影响垃圾收集的对象
WeakReference<String> weakRef = new WeakReference<Stirng>(str);
虚引用(PhantomReference) [ˈfæntəm]
不会决定对象的生命周期,任何时候都可能被垃圾回收器回收。跟踪对象被垃圾回收器回收的活动,起一个哨兵作用,必须和引用队列ReferenceQueue联合使用
引用队列(Reference Queue)
无实际存储结构,存储逻辑 依赖于内部结点之间的关系来表达
存储关联且被GC的软引用,弱引用,虚引用
引用队列的示例代码:
public class NormalObject {
public String name;
public NormalObject(String name) {
this.name = name;
}
@Override
protected void finalize() throws Throwable {
System.out.println("normal object finalize:"+name);
}
}
public class NormalObjectWeakReference extends WeakReference<NormalObject>{
public String name;
public NormalObjectWeakReference(NormalObject normalObject, ReferenceQueue<NormalObject> queue) {
super(normalObject, queue);
this.name = normalObject.name;
}
@Override
protected void finalize() throws Throwable {
System.out.println("NormalObjectWeakReference finalize:"+name);
}
}
public class ReferenceQueueTest {
private static ReferenceQueue<NormalObject> rqQueue = new ReferenceQueue<>();
private static void checkQueue() {
Reference<NormalObject> reference = null;
while ((reference = (Reference<NormalObject>) rqQueue.poll()) != null) {
if (reference != null) {
System.out.println("in queue:"+((NormalObjectWeakReference)reference).name);
System.out.println("reference object :"+reference.get());
}
}
}
public static void main(String[] args) throws InterruptedException {
ArrayList<WeakReference<NormalObject>> weakReferences = new ArrayList<>();
for(int i = 0; i<3; i++) {
weakReferences.add(new NormalObjectWeakReference(new NormalObject("weak"+i),rqQueue ));
System.out.println("create weak:"+weakReferences.get(i));
}
System.out.println("first time");
checkQueue();
System.gc();
Thread.sleep(1000);
System.out.println("second time");
checkQueue();
}
}
结果:
create weak:com.bitongchong.test.NormalObjectWeakReference@7852e922
create weak:com.bitongchong.test.NormalObjectWeakReference@4e25154f
create weak:com.bitongchong.test.NormalObjectWeakReference@70dea4e
first time
normal object finalize:weak1
normal object finalize:weak2
normal object finalize:weak0
second time
in queue:weak2
reference object :null
in queue:weak1
reference object :null
in queue:weak0
reference object :null