WeakHashMap的使用

本文对比分析了WeakHashMap与HashMap的实现原理及使用场景。WeakHashMap使用弱引用存储键值对,适用于不需要长期保存的数据。当键没有强引用时,会触发垃圾回收,从而释放内存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HashMap相信大家都知道,而且应用得非常熟练,但是WeakHashMap不知道有多少人用过,是怎么使用的。最近在看源码的时候发现了WeakHashMap,就想看看这个到底和HashMap有什么不同。

public class WeakHashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable

HashMap比WeakHashMap多实现了Cloneable和Serializable,HashMap让开发者能够去做序列化和反序列化的操作,即可用作为和数据库进行交换的对象。分析WeakHashMap的源码知道它采用的是弱引用的Entry<k,v>进行存储键值对。

/**
     * The entries in this hash table extend WeakReference, using its main ref
     * field as the key.
     */
    private static class Entry<K,V> extends WeakReference<Object> implements Map.Entry<K,V>

那么弱引用关系和强引用关系到底有什么不同呢?看下面代码

public static void main(String[] args) { 
        Map<Thread, String> weakHashMap = new WeakHashMap<Thread, String>();
        
        Thread thread1 = new Thread();
        Thread thread2 = new Thread();
        weakHashMap.put(thread1, "thread1");
        weakHashMap.put(thread2, "thread2");
        thread1 = null;
        System.gc();
        
        for(Entry<Thread, String> entry:weakHashMap.entrySet()){
        	System.out.println(entry.getValue());
        }
        
        Map<Thread, String> hashMap = new HashMap<Thread, String>();
        
        Thread thread3 = new Thread();
        Thread thread4 = new Thread();
        hashMap.put(thread3, "thread3");
        hashMap.put(thread4, "thread4");
        thread3 = null;
        System.gc();
        
        for(Entry<Thread, String> entry:hashMap.entrySet()){
        	System.out.println(entry.getValue());
        }
    }

这里我主动的用垃圾回收进行了处理,得出的结果是:

thread2
thread4
thread3

可以看出WeakHashMap中的thread1被垃圾回收了。但是HashMap的thread3却没有回收。弱引用关系当垃圾回收发生的时候,如果键为null那么就会被回收。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值