Integer做WeakHashMap的Key应注意的问题

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对象(在java编译的时候被自动翻译成Integer.valueOf(int)和使用Integer.valueOf(int)结果一样,说明自动装箱也会利用Integer类的缓存。

在使用Integer或类似的存在缓存的对象作为WeakHashMap的Key的时候,一定要注意对象缓存中对Key对象是否存在无法释放的强引用,否则WeakHashMap自动释放不使用条目的效果无法达到。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值