Create a properly sized ConcurrentHashMap based on the given expected number of elements. - Java java.util

Java examples for java.util:Collection Creation

Description

Create a properly sized ConcurrentHashMap based on the given expected number of elements.

Demo Code

/*/*from   ww w  .  j  a v  a 2  s.co  m*/
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
 */
//package com.java2s;

import java.util.concurrent.ConcurrentHashMap;

public class Main {
    public static void main(String[] argv) {
        int expectedNumberOfElements = 42;
        System.out.println(concurrentMap(expectedNumberOfElements));
    }

    public static final float LOAD_FACTOR = 0.75f;

    /**
     * Create a properly sized {@link ConcurrentHashMap} based on the given expected number of elements.
     *
     * @param expectedNumberOfElements The expected number of elements for the created map
     * @param <K> The map key type
     * @param <V> The map value type
     *
     * @return The created map.
     */
    public static <K, V> ConcurrentHashMap<K, V> concurrentMap(
            int expectedNumberOfElements) {
        return concurrentMap(expectedNumberOfElements, LOAD_FACTOR);
    }

    /**
     * Create a properly sized {@link ConcurrentHashMap} based on the given expected number of elements and an
     * explicit load factor
     *
     * @param expectedNumberOfElements The expected number of elements for the created map
     * @param loadFactor The collection load factor
     * @param <K> The map key type
     * @param <V> The map value type
     *
     * @return The created map.
     */
    public static <K, V> ConcurrentHashMap<K, V> concurrentMap(
            int expectedNumberOfElements, float loadFactor) {
        final int size = expectedNumberOfElements + 1
                + (int) (expectedNumberOfElements * loadFactor);
        return new ConcurrentHashMap<K, V>(size, loadFactor);
    }
}

Related Tutorials