Java 四大引用
时间:2024-01-05 03:07:01
目录
1.强引用(StrongReference)
2.软引用(SoftReference)
3.弱引用(WeakReference)
4.虚引用(PhantomReference)
5.案例:
从高到低高到低分别为:强引用、软引用、弱引用和虚引用
1.强引用(StrongReference)
2.软引用(SoftReference)
3.弱引用(WeakReference)
4.虚引用(PhantomReference)
5.案例:
public class Demo1 { public static void main(String[] args) { ///这是强引用 String str = "hello"; //现在我们通过以上强引用创建软引用,所以现在 str 有两个引用指向它 SoftReference soft = new SoftReference(str); str = null; //可用 get()引用指向对象 System.out.println(soft.get();//输出 hello } }
public class Demo2 { public static void main(String[] args) { ///这是强引用 String str="hello"; ReferenceQueue super String> q=new ReferenceQueue(); //现在我们通过上面的强引用创造了一个虚引用,所以现在 str 有两个引用指向它 PhantomReference p=new PhantomReference(str, q); //可用 get()引用指向对象 System.out.println(q.poll();//输出 null } }
public class Store {
public static final int SIZE = 10000;
private double[] arr = new double[SIZE];
private String id;
public Store() {
}
public Store(String id) {
super();
this.id = id;
}
@Override
protected void finalize() throws Throwable {
System.out.println(id + "被回收了");
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return id;
}
}
public class Demo3 {
public static ReferenceQueue queue = new ReferenceQueue();
public static void checkQueue() {
if (queue != null) {
@SuppressWarnings("unchecked")
Reference ref = (Reference) queue.poll();
if (ref != null)
System.out.println(ref + "......" + ref.get());
}
}
public static void main(String[] args) {
HashSet> hs1 = new HashSet>();
HashSet> hs2 = new HashSet>();
//创建 10 个软引用
for (int i = 1; i <= 10; i++) {
SoftReference soft = new SoftReference(new
Store("soft" + i), queue);
System.out.println("create soft" + soft.get());
hs1.add(soft);
}
System.gc();
checkQueue();
//创建 10 个弱引用
for (int i = 1; i <= 10; i++) {
WeakReference weak = new WeakReference(new
Store("weak" + i), queue);
System.out.println("create weak" + weak.get());
hs2.add(weak);
}
System.gc();
checkQueue();
//创建 10 个虚引用
HashSet> hs3 = new
HashSet>();
for (int i = 1; i <= 10; i++) {
PhantomReference phantom = new PhantomReference(new
Store("phantom" + i), queue);
System.out.println("create phantom " + phantom.get());
hs3.add(phantom);
}
System.gc();
checkQueue();
}
}

可以看到虚引用和弱引用被回收掉。。。