System.gc()


int length = 3;
Set<Sky> a = new HashSet<Sky>();
for (int i = 0; i < length; i++) {
Sky ref = new Sky("Hard_" + i);
System.out.println("创建强引用:" + ref);
a.add(ref);
}

System.gc();

Set<SoftReference<Sky>> sa = new HashSet<SoftReference<Sky>>();
for (int i = 0; i < length; i++) {
SoftReference<Sky> ref = new SoftReference<Sky>(
new Sky("Soft_" + i));
System.out.println("创建软引用:" + ref.get());
sa.add(ref);
}
// sa=null;
System.gc();

Set<WeakReference<Sky>> wa = new HashSet<WeakReference<Sky>>();
for (int i = 0; i < length; i++) {
WeakReference<Sky> ref = new WeakReference<Sky>(
new Sky("Weak_" + i));
System.out.println("创建弱引用:" + i);
wa.add(ref);
}

System.gc();

ReferenceQueue<Sky> rq = new ReferenceQueue<Sky>();
Set<PhantomReference<Sky>> pa = new HashSet<PhantomReference<Sky>>();
for (int i = 0; i < length; i++) {
PhantomReference<Sky> ref = new PhantomReference<Sky>(new Sky(
"Phantom_" + i), rq);
System.out.println("创建虚拟引用:" + ref.get());
pa.add(ref);
}
System.gc();




public class Sky {

public Sky(String id){
this.id=id;
}
private String id;

public String getId() {
return id;
}

@Override
public String toString(){
return id;
}

@Override
protected void finalize() throws Throwable {

System.out.println("回收对象"+id);
}


}


创建强引用:Hard_0
创建强引用:Hard_1
创建强引用:Hard_2
创建软引用:Soft_0
创建软引用:Soft_1
创建软引用:Soft_2
创建弱引用:0
创建弱引用:1
创建弱引用:2
创建虚拟引用:null
创建虚拟引用:null
创建虚拟引用:null
回收对象Weak_2
回收对象Weak_1
回收对象Weak_0
回收对象Phantom_2
回收对象Phantom_1
回收对象Phantom_0


System.gc() 只是对于弱引用和虚引用具有立竿见影的效果。
强引用并没有相应的引用类,彩一般形式创建的对象便属于强引用类型。
在创建对象时将其设置为弱引用,可以有效地加快对象所战胜的内存空间被JVM垃圾收集器回收的速度。
虚拟引用并不是一种真正的对象引用,所以通过Reference对象的get()方法从引用中获取的对象都是null
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值