• 如果让你来做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

    参考:

    江南白衣:高性能下,map家族优化建议

  • 相关阅读:
    poj3905 2sat!
    poj3648,2-sat求解
    poj2723 2sat判断解+二分
    hdu3622 2-sat问题,二分+判断有无解即可。
    poj2767,单向连通图判定,缩点+重新建图+新图DFS
    poj2186 求有向图G中所有点都能到达的点的数量
    poj2553 有向图缩点,强连通分量。
    poj 1236+hdu2767 有向图 缩点+看度数(tarjan)
    poj3694+hdu2460 求桥+缩点+LCA/tarjan
    dfs + 最小公倍数 Codeforces Round #383 (Div. 2)
  • 原文地址:https://www.cnblogs.com/yuyutianxia/p/6255658.html
Copyright © 2020-2023  润新知