您的位置:首页 > 其它

Integer做WeakHashMap的Key应注意的问题

2014-05-16 10:46 246 查看
WeakHashMap使用弱引用来作为Map的Key,利用虚拟机的垃圾回收机制能自动释放Map中没有被使用的条目。但是WeakHashMap释放条目是有条件的:首先条目的Key在系统中没有强引用指向;另外,条目的释放是在垃圾回收之后第一次访问这个WeakHashMap时完成的。

而当我们想要获取一个Integer对象时,为了利用Integer类本身的缓存,减少堆中Integer对象的重复申请和释放,我们通常会采用Ingeter.valueOf(int)方法来获取Integer对象,而不是直接使用new Integer(int)。 Integer类会将0~127的整数对象缓存在一个Map中,而这个Map中保存的是这些Integer对象的强引用,如果我们想要使用Integer作为WeakHashMap的Key,那就需要注意不能再使用Integer.valueOf(int)方法获取WeakHashMap中Key的对象,否则所有以0~127作为Key的条目不会被自动释放。

下面一段代码比较了三种方式获取到的Integer对象分别作为WeakHashMap的Key的区别,三种方式分别是:1.使用Integer.valueOf(int);2.使用new Integer(int);3.使用Java的自动装箱。

public static void main(String[] args) {
// TODO Auto-generated method stub
Map<Integer, String> wmap = new WeakHashMap<Integer, String>();
for(int i = 0; i <= 160; i += 20){
wmap.put(Integer.valueOf(i), "" + i);
}

System.out.println("Before GC1: ");
System.out.println(wmap);
System.gc();
System.out.println("After GC1: ");
System.out.println(wmap);

wmap.clear();
for(int i = 0; i <= 160; i += 20){
wmap.put(new Integer(i), "" + i);
}
System.out.println("Before GC2: ");
System.out.println(wmap);
System.gc();
System.out.println("After GC2: ");
System.out.println(wmap);

wmap.clear();
for(int i = 0; i <= 160; i += 20){
wmap.put(i, "" + i);
}
System.out.println("Before GC3: ");
System.out.println(wmap);
System.gc();
System.out.println("After GC3: ");
System.out.println(wmap);

}


运行结果如下:

Before GC1:
{120=120, 60=60, 160=160, 40=40, 140=140, 80=80, 20=20, 100=100, 0=0}
After GC1:
{120=120, 60=60, 40=40, 80=80, 20=20, 100=100, 0=0}
Before GC2:
{120=120, 60=60, 160=160, 40=40, 140=140, 80=80, 20=20, 100=100, 0=0}
After GC2:
{}
Before GC3:
{120=120, 60=60, 160=160, 40=40, 140=140, 80=80, 20=20, 100=100, 0=0}
After GC3:
{120=120, 60=60, 40=40, 80=80, 20=20, 100=100, 0=0}


  可以看到第一种方式使用Integer.valueOf(int)得到的Key,垃圾回收之后只释放了140和160两个条目,128一下都仍然保留;使用new Integer(int)得到的Key垃圾回收之后全部被释放。值得注意的是,我们利用自动装箱得到的Integer对象和使用Integer.valueOf(int)结果一样,说明自动装箱也会利用Integer类的缓存。在使用Integer或类似的存在缓存的对象作为WeakHashMap的Key的时候,一定要注意对象缓存中对Key对象是否存在无法释放的强引用,否则WeakHashMap自动释放不使用条目的效果无法达到。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: