package jdk.math;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.WeakHashMap;
/**
* Created by yesh on 2015/4/5.
*/
public class TestWeekHashMap {
public static void main(String[] args) {
testDemo();
testWeakReference();
}
/***
* 输出的结果如下:
* java.lang.Object@56f631
* null
* null
* java.lang.ref.WeakReference@1a06e38
*/
public static void testWeakReference(){
Object obj = new Object();
ReferenceQueue<Object> queue = new ReferenceQueue<Object>();
WeakReference<Object> weakReference = new WeakReference<Object>(obj,queue);
obj = null;
System.out.println(weakReference.get());
System.out.println(queue.poll());
System.gc();
System.runFinalization();
System.out.println(weakReference.get());
System.out.println(queue.poll());
}
/**
* 输出的结果是1,0
* WeakHashMap中当key值除了map中指向该值没有其它的地方引用
* 就会在Map自动删除该值
*/
public static void testDemo() {
WeakHashMap<Object, Object> map = new WeakHashMap<Object,Object>();
Object value = new Object();
Object key = new Object();
map.put(key,value);
key = null; //当Key指定为null时
System.out.println(map.size());
System.gc(); //进行gc处理
System.runFinalization();
System.out.println(map.size());
}
}
WeakHashMap的基本使用方法
最新推荐文章于 2024-09-19 02:38:44 发布