package CH02;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
import java.util.Set;
import java.util.HashSet;
public class TestReferences
{
public static void main(String[] args)
{
int length=10;
//创建length个MyObject对象的强引用
Set<MyObject> a = new HashSet<MyObject>();
for(int i = 0; i < length; i++)
{
MyObject ref=new MyObject("Hard_" + i);
System.out.println("创建强引用:" +ref);
a.add(ref);
}
//a=null;
System.gc();
//创建length个MyObject对象的软引用
Set<SoftReference<MyObject>> sa = new HashSet<SoftReference<MyObject>>();
for(int i = 0; i < length; i++)
{
SoftReference<MyObject> ref=new SoftReference<MyObject>(new MyObject("Soft_" + i));
System.out.println("创建软引用:" +ref.get());
sa.add(ref);
}
System.gc();
//创建length个MyObject对象的弱引用
Set<WeakReference<MyObject>> wa = new HashSet<WeakReference<MyObject>>();
for(int i = 0; i < length; i++)
{
WeakReference<MyObject> ref=new WeakReference<MyObject>(new MyObject("Weak_" + i));
System.out.println("创建弱引用:" +ref.get());
wa.add(ref);
}
System.gc();
//创建length个MyObject对象的虚引用
ReferenceQueue<MyObject> rq = new ReferenceQueue<MyObject>();
Set<PhantomReference<MyObject>> pa = new HashSet<PhantomReference<MyObject>>();
for(int i = 0; i < length; i++)
{
PhantomReference<MyObject> ref = new PhantomReference<MyObject>(new MyObject("Phantom_" + i), rq);
System.out.println("创建虚引用:" +ref.get());
pa.add(ref);
}
System.gc();
}
}
class MyObject
{
private String id;
public MyObject(String id)
{
this.id = id;
}
public String toString()
{
return id;
}
public void finalize()
{
System.out.println("回收对象:" + id);
}
}
结果:
创建强引用:Hard_0
创建强引用:Hard_1
创建强引用:Hard_2
创建强引用:Hard_3
创建强引用:Hard_4
创建强引用:Hard_5
创建强引用:Hard_6
创建强引用:Hard_7
创建强引用:Hard_8
创建强引用:Hard_9
创建软引用:Soft_0
创建软引用:Soft_1
创建软引用:Soft_2
创建软引用:Soft_3
创建软引用:Soft_4
创建软引用:Soft_5
创建软引用:Soft_6
创建软引用:Soft_7
创建软引用:Soft_8
创建软引用:Soft_9
创建弱引用:Weak_0
创建弱引用:Weak_1
创建弱引用:Weak_2
创建弱引用:Weak_3
创建弱引用:Weak_4
创建弱引用:Weak_5
创建弱引用:Weak_6
创建弱引用:Weak_7
创建弱引用:Weak_8
创建弱引用:Weak_9
回收对象:Weak_1
回收对象:Weak_9
回收对象:Weak_8
回收对象:Weak_7
回收对象:Weak_6
回收对象:Weak_5
回收对象:Weak_4
回收对象:Weak_3
回收对象:Weak_2
回收对象:Weak_0
创建虚引用:null
创建虚引用:null
创建虚引用:null
创建虚引用:null
创建虚引用:null
创建虚引用:null
创建虚引用:null
创建虚引用:null
创建虚引用:null
创建虚引用:null
回收对象:Phantom_1
回收对象:Phantom_9
回收对象:Phantom_8
回收对象:Phantom_7
回收对象:Phantom_6
回收对象:Phantom_5
回收对象:Phantom_4
回收对象:Phantom_3
回收对象:Phantom_2
回收对象:Phantom_0