JDK6.0学习笔记(二)垃圾收集机制-对象引用的类型
来源:互联网 发布:vb.net 资源文件exe 编辑:程序博客网 时间:2024/05/22 17:45
- 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;
-
- 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);
- }
-
- System.gc();
-
- 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();
- }
- }
- class MyObject {
- private String id;
- public MyObject(String id) {
- this.id = id;
- }
- public String toString() {
- return id;
- }
- public void finalize() {
- System.out.println("回收对象:" + id);
- }
- }