惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
PCI Perspectives
PCI Perspectives
Webroot Blog
Webroot Blog
Help Net Security
Help Net Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Hacker News: Ask HN
Hacker News: Ask HN
Security Latest
Security Latest
P
Palo Alto Networks Blog
Spread Privacy
Spread Privacy
S
Securelist
V2EX - 技术
V2EX - 技术
Schneier on Security
Schneier on Security
P
Proofpoint News Feed
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Forbes - Security
Forbes - Security
N
News | PayPal Newsroom
Cyberwarzone
Cyberwarzone
C
Cisco Blogs
Cloudbric
Cloudbric
GbyAI
GbyAI
A
About on SuperTechFans
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Vercel News
Vercel News
P
Proofpoint News Feed
SecWiki News
SecWiki News
T
Tailwind CSS Blog
腾讯CDC
C
Cybersecurity and Infrastructure Security Agency CISA
The Hacker News
The Hacker News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
M
MIT News - Artificial intelligence
爱范儿
爱范儿
Microsoft Azure Blog
Microsoft Azure Blog
T
Troy Hunt's Blog
G
Google Developers Blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cisco Talos Blog
Cisco Talos Blog
D
DataBreaches.Net
V
Vulnerabilities – Threatpost
博客园 - 叶小钗
C
Check Point Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Know Your Adversary
Know Your Adversary
T
Tor Project blog
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
Y
Y Combinator Blog
H
Help Net Security
Latest news
Latest news

博客园 - cacard

Android中的内部类引起的内存泄露 Android的消息机制: Message/MessageQueue/Handler/Looper ArrayList/Vector的原理、线程安全和迭代Fail-Fast JVM中的Stack和Frame JVM中的垃圾收集算法和Heap分区简记 无锁编程以及CAS 简述Java内存模型的由来、概念及语义 MQTT协议简记 RabbitMQ的工作队列和路由 RabbitMQ 入门 [Java] LinkedHashMap 源码简要分析 [Java] HashMap 源码简要分析 CentOS 安装 Hadoop 手记 树莓派(RespberryPi)安装手记 RPC简述 [C++] const与重载 [C++] 左值、右值、右值引用 [C++] 引用 Java线程池 / Executor / Callable / Future
[Java] Hashtable 源码简要分析
cacard · 2014-03-06 · via 博客园 - cacard

Hashtable /HashMap / LinkedHashMap 概述

* Hashtable比较早,是线程安全的哈希映射表。内部采用Entry[]数组,每个Entry均可作为链表的头,用来解决冲突(碰撞)。

* HashMap与Hashtable基本原理一样,只是HashMap允许null的key/value,且非线程安全。

* LinkedHashMap从字面看有两个意思,Hash和Linked,既通过Hash散列存储(与HashMap相同),又把每个Entry(增加了before/after指针)通过双向链表进行连接,记录元素插入的顺序。根据Key取数据,可按照HashMap的散列迅速定位Value;迭代时,可按照双向链表,高效遍历。

Hashtable 特点

* 线程安全。

* Key、Value均不能为null。

* 包含了一个Entry[]数组,而Entry又是一个链表,用来处理冲突。

* 每个Key对应了Entry数组中固定的位置(记为index),称为槽位(Slot)。槽位计算公式为: (key.hashCode() & 0x7FFFFFFF) % Entry[].length() 。

* 当Entry[]的实际元素数量(Count)超过了分配容量(Capacity)的75%时,新建一个Entry[]是原先的2倍,并重新Hash(rehash)。

* rehash的核心思路是,将旧Entry[]数组的元素重新计算槽位,散列到新Entry[]中。

Hashtable 源码简要分析

Entry类

 
class Entry<K,V> // Entry<K,V>是槽中的元素,可做链表,解决散列冲突。
{
     int hash; // 即key.hashCode()
     K key;
     V value;
     Entry<K,V> next; // 用来实现链表结构。同一链表中的key的hash是相同的。
     protected Entry(int hash, K key, V value, Entry<K,V> next) {
          this.hash=hash;this.key=key;this.value=value;this.next=next;
     }
}

Hashtable类

public class Hashtable<K,V>
{
     Entry[] table; // 槽数组,也称桶数组。
     int count; // table中实际存放的Entry数量。
     int threshold; // 当table数量超过该阈值后,进行reash。(该值为 capacity * loadFactor)
     float loadFactor; // 加载因子,默认是0.75f。

     public Hashtable(int initialCapacity/*默认是11*/, float loadFactor) {
          if(initialCapacity==0) initialCapacity=1;
          this.locadFactor = locadFactor;
          table = new Entry[initialCapacity];
          threshold = (int)(initialCapacity * locadFactor);
     }

     // put(): 若key存在,返回旧value;若key不存在,返回null。
     public synchronized V put(K key,V value) {
          // 检查key是否已经存在,若存在则覆盖已经存在value,并返回被覆盖的value。
          Entry tab[] = table;
          int hash = key.hashCode();
          int index = (hash & 0x7FFFFFFF) % tab.length; // 存储槽位索引。 
          for(Entry<K,V> e = tab[index]; e!=null; e=e.next ) { // 在冲突链表中寻找
               if( (e.hash == hash ) && e.key.equals(key) ) {
                         V old = e.value;
                         e.value = value; // 新value覆盖旧value
                         return old;
                    }
          }

          // 是否需要rehash
          if(count >= threshold){
               rehash();
               tab = table; // rehash完毕后,修正tab指针指向新的Entry[]
               index =  (hash & 0x7FFFFFFF) % tab.length; // 重新计算Slot的index
          }

          // 存储到槽位,如果有冲突,新来的元素被放到了链表前面。
          Entry<K,V> e = tab[index]; // 旧有Entry
          tab[index] = new Entry<>(hash,key,value,e/* 旧有Entry成为了新增Entry的next */);
          count ++;
          return null;
     }

     // rehash(): 再次hash。当Entry[]的实际存储数量占分配容量的约75%时,扩容并且重新计算各个对象的槽位
     static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8 ;
     protected void rehash() {
          int oldCapacity = table.length;
          Entry[] oldMap = table;
          int newCapacity = (oldCapacity << 1) + 1; // 2倍+1
          Entry[] newMap = new Entry[newCapacity];
          threshold = (int)(newCapacity * loadFactor);
          table = newMap;

          for( int i=oldCapacity; i-- >0;){ //  i的取值范围为 [oldCapacity-1,0]
               for (Entry<K,V> old = oldMap[i]; old!=null;){ // 遍历旧Entry[]
                    Entry<K,V> e = old;
                    int index = (e.hash & 0x7FFFFFFF) % newCapacity;     // 重新计算各个元素在新Entry[]中的槽位index。
                    e.next = newMap[index]; // 已经存在槽位中的Entry放到当前元素的next中
                    newMap[index]=e;     // 放到槽位中
                    old = old.next;
               }
          }

     }
}

References

JDK源码