基础数据机构之WeakHashMap源码分析
来源:互联网 发布:万德数据库电话 编辑:程序博客网 时间:2024/06/05 04:23
1.WeakHashMap 在HashMap实现上,在HashMap上增加Entry的SoftReference软引用功能
源码分析
Entry实体类继承WeakReference
/** * The entries in this hash table extend WeakReference, using its main ref * field as the key. */ private static class Entry<K,V> extends WeakReference<K> implements Map.Entry<K,V> {//继承WeakReference弱引用 private V value; private final int hash; private Entry<K,V> next; /** * Creates new entry. */ Entry(K key, V value,ReferenceQueue<K> queue,int hash, Entry<K,V> next) { super(key, queue); this.value = value; this.hash = hash; this.next = next; }
public K getKey() { return WeakHashMap.<K>unmaskNull(get());//get()方法,获取该key的时候,判断是否被回收掉,如果被回收掉返回null }}
插入数据方式和HashMap插入数据方法一致,只是多了对WeakReference的null判断逻辑
/** * Associates the specified value with the specified key in this map. * If the map previously contained a mapping for this key, the old * value is replaced. * * @param key key with which the specified value is to be associated. * @param value value to be associated with the specified key. * @return the previous value associated with <tt>key</tt>, or * <tt>null</tt> if there was no mapping for <tt>key</tt>. * (A <tt>null</tt> return can also indicate that the map * previously associated <tt>null</tt> with <tt>key</tt>.) */ public V put(K key, V value) { K k = (K) maskNull(key);//如果该key为null,那么直接使用NULL_KEY作为填充 int h = HashMap.hash(k.hashCode()); Entry[] tab = getTable(); int i = indexFor(h, tab.length); for (Entry<K,V> e = tab[i]; e != null; e = e.next) { if (h == e.hash && eq(k, e.get())) { V oldValue = e.value; if (value != oldValue) e.value = value; return oldValue; } } modCount++;Entry<K,V> e = tab[i]; tab[i] = new Entry<K,V>(k, value, queue, h, e); if (++size >= threshold) resize(tab.length * 2); return null; }
阅读全文
0 0
- 基础数据机构之WeakHashMap源码分析
- 基础数据机构之Stack栈源码分析
- 基础数据机构之ArrayDeque队列源码分析
- jdk源码分析之WeakHashMap
- 《Java源码分析》:WeakHashMap
- WeakHashMap源码分析
- 《Java源码分析》:WeakHashMap
- WeakHashMap源码分析
- java-EnumMap、IdentityHashMap、WeakHashMap源码分析
- WeakHashMap实现原理及源码分析
- WeakHashMap分析
- 数据机构之优先级队列
- Java-Collection源码分析(九)——WeakHashMap
- Java 集合系列13之 WeakHashMap源码解析
- JDK源码学习之集合HashMap、Hashtable、WeakHashMap比较
- WeakHashMap类源码解析
- Java8 - WeakHashMap源码
- Java WeakHashMap 源码解析
- apicloud中bMap模块应用
- CSDN如何转载别人的文章
- 设计模式 装饰者模式 带你重回传奇世界
- Python的zip函数
- Mybatis中的resultType和resultMap
- 基础数据机构之WeakHashMap源码分析
- 使用doc4j生成word文档
- 【Spring+SpringMVC+MyBatis深入学习及搭建】11.SpringMVC架构
- MySQL数据类型和常用字段属性总结
- java实现敏感词过滤
- 【WPF】UI虚拟化之------自定义VirtualizingWrapPanel
- discuz论坛用户--设置--修改头像不显示
- 微信开发遇到的问题及解决
- java 文件上传