简体   繁体   English

ConcurrentHashMap超过容量

[英]ConcurrentHashMap over the capacity

I am a new learner about the ConcurrentHashMap. 我是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. 我将ConcurrentHashMap的初始容量设置为1,然后我将10个值放入其中。 So in my opinion, the ConcurrentHashMap will only receive the first and deny the rest of 9; 所以在我看来,ConcurrentHashMap只接收第一个并拒绝其余的9个; however, when I print the map and I find all 10 values have been stored in map. 但是,当我打印地图时,我发现所有10个值都已存储在地图中。 So is it no use of the initial capacity parameter or the ConcurrentHashMap can increase itself if reach the capacity? 那么它是否没有使用初始容量参数,或者如果达到容量,ConcurrentHashMap可以自行增加?

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. 让我们说你需要一个哈希映射,它将包含稳定状态下的100万个密钥。 Then you would probably initialize the hash map with 50k size. 然后你可能会用50k大小初始化哈希映射。

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. 另一方面,如果您的哈希映射只包含稳定状态下的1000个键,那么您可能会使用较小的值进行初始化。

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). 假设linear resizing ,对于100万个键,如果初始化值为50,那么每次添加50个元素时,java必须调整大小(这将涉及复制)。 The number of resizing would be roughly 20. But if you had initialized with a value as 500, you would have resized only twice. 调整大小的数量大约为20.但如果您使用值初始化为500,则只调整两次。

The JVM increases the size automatically. JVM会自动增加大小。 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. 如果您确定要向其添加至少X个项目,则将其初始化为该容量。 JVM will take care of resizing it for you as the need may be. JVM将根据需要为您调整大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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