简体   繁体   中英

ConcurrentHashMap over the capacity

I am a new learner about the ConcurrentHashMap. Now I write the following code:

ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap(1);

for(int i=0; i<10; i++){
    map.put(i,i);
}

//print map

I set the initial capacity of ConcurrentHashMap to 1, and after that I put 10 values into it. So in my opinion, the ConcurrentHashMap will only receive the first and deny the rest of 9; however, when I print the map and I find all 10 values have been stored in map. So is it no use of the initial capacity parameter or the ConcurrentHashMap can increase itself if reach the capacity?

the initial capacity is an rough estimate of how many elements the hash map would contain. Once you start to add more elements the size of the hash map will increase (either linearly or exponentially). Increasing the size of the hash map has a overhead.

Lets say you need a hash map which will contain 1 million keys in steady state. Then you would probably initialize the hash map with 50k size.

On the other hand if you your hash map will contain only 1000 keys in steady state, then you would probably initialize with a small value.

EDIT:

Assuming linear resizing , for 1 million keys if you initialize with a value of 50, then every time you add 50 elements java have to resize (which would involve copying). The number of resizing would be roughly 20. But if you had initialized with a value as 500, you would have resized only twice.

The JVM increases the size automatically. Capacity is simply used to initialize whatever collection backs the map to a certain size. If you know for sure you are going to be adding at least X number of items to it then initialize it to that capacity. JVM will take care of resizing it for you as the need may be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM