How to use and set appropriately concurrency level for ConcurrentHashMap?

后端 未结 5 1735
遥遥无期
遥遥无期 2020-12-17 09:20

I am working with around 1000 elements in concurrenthashmap . Default concurrency level is 16 . can anyone help me with some algorithm or factors from which i can identify t

5条回答
  •  时光取名叫无心
    2020-12-17 09:54

    Java 8:

    Now the ConcurrentHashMap does not use a fixed lock striping scheme at all, instead each bucket serves as a “stripe” using intrinsic synchronization.

    Code from source:

    /** Implementation for put and putIfAbsent */
    final V putVal(K key, V value, boolean onlyIfAbsent) {
        ...
        Node f; int n, i, fh;
        ...
        else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
        ...
           synchronized (f) {
               ...
           }
    }
    

    And the constructor has the parameter just use it as a size hint as docs say.

    concurrencyLevel - the estimated number of concurrently updating threads. The implementation may use this value as a sizing hint.

    And the source:

    public ConcurrentHashMap(int initialCapacity,
                             float loadFactor, int concurrencyLevel) {
        if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0)
            throw new IllegalArgumentException();
        if (initialCapacity < concurrencyLevel)   // Use at least as many bins
            initialCapacity = concurrencyLevel;   // as estimated threads
        long size = (long)(1.0 + (long)initialCapacity / loadFactor);
        int cap = (size >= (long)MAXIMUM_CAPACITY) ?
            MAXIMUM_CAPACITY : tableSizeFor((int)size);
        this.sizeCtl = cap;
    }
    

    So you don't need to consider it by yourself, ConcurrentHashMap will handle it for you.

提交回复
热议问题