垃圾回收 GC
public class MyObject {
private String id;
public MyObject(String id) {
this.id = id;
}
@Override
public String toString() {
return "MyObject{" +
"id='" + id + '\'' +
'}';
}
public void finalize() {
System.out.println("对象回收"+id);
}
}
引用类型 1.强引用
2.软引用
3.弱引用
4.虚引用
输出结果
源码
public class GCTest {
public static void main(String[] args){
int length =5;
//--------------创建强引用------------
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;
//------------- 创建软引用-------------
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();
//------------- 创建弱引用-------------
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();
//------------- 创建虚引用-------------
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();
}
}