• 技术文章 >Java >java教程

    如何在Java中使用ConcurrentHashMap?

    PHPzPHPz2023-04-26 14:34:07转载20

    说明

    1、ConcurentHashMap结合了HashMap和Hashtable的优点。HashMap不考虑同步,Hashtable考虑同步。但是Hashtable每次同步都要锁定整个结构。

    2、ConcurentHashMap锁的方式是稍微细粒度的。ConcurentHashMap将hash表分成16桶(默认值),如get、put、remove等常用操作只锁定目前需要的桶。

    实例

    /**
         * Creates a new, empty map with the default initial table size (16).
         */
        public ConcurrentHashMap() {
        }
     
        /**
         * Creates a new, empty map with an initial table size
         * accommodating the specified number of elements without the need
         * to dynamically resize.
         *
         * @param initialCapacity The implementation performs internal
         * sizing to accommodate this many elements.
         * @throws IllegalArgumentException if the initial capacity of
         * elements is negative
         */
        public ConcurrentHashMap(int initialCapacity) {
            if (initialCapacity < 0)
                throw new IllegalArgumentException();
            int cap = ((initialCapacity >= (MAXIMUM_CAPACITY >>> 1)) ?
                       MAXIMUM_CAPACITY :
                       tableSizeFor(initialCapacity + (initialCapacity >>> 1) + 1));
            this.sizeCtl = cap;
        }
     
        /**
         * Creates a new map with the same mappings as the given map.
         *
         * @param m the map
         */
        public ConcurrentHashMap(Map<? extends K, ? extends V> m) {
            this.sizeCtl = DEFAULT_CAPACITY;
            putAll(m);
        }

    以上就是如何在Java中使用ConcurrentHashMap?的详细内容,更多请关注php中文网其它相关文章!

    声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除
    专题推荐:Java concurrenthashmap
    上一篇:Java中接口的作用是什么? 下一篇:自己动手写 PHP MVC 框架(40节精讲/巨细/新人进阶必看)

    相关文章推荐

    • Java 中的各种锁有哪些?• Java代码块的使用细节有哪些• Java Web项目访问不到html文件怎么解决• java ArrayList集合的扩容机制• Java怎么以编程方式实现JAR文件的创建
    1/1

    PHP中文网