[英]How can I avoid growing my hashmaps to 2 keys until I try to add a second key?
I have a situation where I have tons of hashmaps (millions and millions) in my server, and 95% of them have literally only one key, ever.我有一种情况,我的服务器中有大量的哈希图(数以百万计),而其中 95% 从字面上看只有一个键。
The server runs out of memory;服务器内存不足; which probably may have something to do with the fact that initial HashMap default size is 16, so for every HashMap object I'm wasting a ton of memory.
这可能与初始 HashMap 默认大小为 16 的事实有关,因此对于每个 HashMap 对象,我都在浪费大量内存。
Short of re-designing the server with a new data structure that flexibly stores the data as 1 element OR an entire hashmap (which I'd prefer avoiding), I'm trying to first optimize this by changing the initial size to 1:没有使用新的数据结构重新设计服务器,灵活地将数据存储为 1 个元素或整个哈希图(我更愿意避免),我试图首先通过将初始大小更改为 1 来优化它:
Map<String, Type2> myMiniMap = new HashMap<>(1);
However, my concern is that due to default load factor of 0.75 in HashMaps, this would immediately get increased to 2 the moment I add the first key to the map (since 1*0.75 < 1
, which is how I understand hash sizing logic in Java)但是,我担心的是,由于 HashMaps 中的默认加载因子为 0.75,当我将第一个键添加到映射时,它会立即增加到 2(因为
1*0.75 < 1
,这就是我理解哈希大小逻辑的方式爪哇)
Assuming my understanding above is correct (that by default, Java will create a space for 2 keys as soon as I add the first key to the hash), is there a way to prevent this from happening till I actually try to insert the second key ?假设我上面的理解是正确的(默认情况下,一旦我将第一个键添加到哈希中,Java 就会为 2 个键创建一个空间),有没有办法防止这种情况发生,直到我实际尝试插入第二个键?
Eg, should I set loadFactor to zero or one?例如,我应该将 loadFactor 设置为零还是一?
If they're truly only ever going to be singletons, why not use Collections.singletonMap
to create them?如果它们真的只会成为单身人士,为什么不使用
Collections.singletonMap
来创建它们呢? The downside of this is that the map that is created is immutable.这样做的缺点是创建的地图是不可变的。
Alternatively, you could create your own class implementing Map
that will store a key and value in class fields and then, if an attempt is made to add a second key value, it will switch to using a HashMap
as its default backing store.或者,您可以创建自己的实现
Map
的类,该类将在类字段中存储键和值,然后,如果尝试添加第二个键值,它将切换为使用HashMap
作为其默认后备存储。 It would be more tedious than difficult to accomplish.这将比完成更乏味。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.