如果让你来做HashMap扩容,如何实现在不影响读写的情况下扩容?
1.了解HashMap的实现;如果一个面试者了解这一点,说明至少他关心过java提供的数据类型的实现,甚至极可能看过源码,他应该不会是一个纯粹的苦力
2.知道"不影响读写的情况下扩容"是什么含义,说明他在工作中了解多线程的相关知识
3.如果他能提到ConcurrentHashMap中的相关内容,说明他日常编程中有使用到concurrent包,可以继续聊聊,否则他对多线程的使用可能非常初级
4.如果他能提出一些解决方案,即使不完整,也能看出他对类似CAS、分布式一致性等问题的了解程度
一、org.apache.commons.collections.FastHashMap
A customized implementation of java.util.HashMap
designed to operate in a multithreaded environment where the large majority of method calls are read-only, instead of structural changes. When operating in "fast" mode, read calls are non-synchronized and write calls perform the following steps:
- Clone the existing collection
- Perform the modification on the clone
- Replace the existing collection with the (modified) clone
public Object put(Object key, Object value) { if (fast) { synchronized (this) { HashMap temp = (HashMap) map.clone(); Object result = temp.put(key, value); map = temp; return (result); } } else { synchronized (map) { return (map.put(key, value)); } } }
二、io.netty.util.collection.IntObjectHashMap
区别并不仅仅在于int 换 Integer的那点空间,而是整个存储结构和Hash冲突的解决方法都不一样。
HashMap的结构是 Node[] table; Node 下面有Hash,Key,Value,Next四个属性。
而IntObjectHashMap的结构是int[] keys 和 Object[] values.
在插入时,同样把int先取模落桶,如果遇到冲突,则不采样HashMap的链地址法,而是用开放地址法(线性探测法)index+1找下一个空桶,最后在keys[index],values[index]中分别记录。在查找时也是先落桶,然后在key[index++]中逐个比较key。
所以,对比整个数据结构,省的不止是int vs Integer,还有每个Node的内容。
而性能嘛,IntObjectHashMap还是稳赢一点的,随便测了几种场景,耗时至少都有24ms vs 28ms的样子,好的时候甚至快1/3。
三、ConcurrentHashMap
参考: