如何正确使用concurrenthashmap?
比如说,我有很多读取操作和一些写入操作,并且将放置在映射中的对象相当“重”——此类对象的初始化会消耗大量内存/时间等。
我应该如何编码才能既利用并发哈希图的高性能,又确保这些缓存对象的不必要初始化的成本最小。
欢迎并非常感谢示例代码片段! 谢谢!
say, I have a lot of read operations and a few write operations, and the object which will be placed in map is quite "heavy"-initialization of such object costs much memory/time,etc.
how should I code to both utilize the high performance of concurrenthashmap and ensure a minimum cost of unnecessary initialization of those cached objects.
sample code snippet is welcome and greatly appreciate!
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
很确定 guava 正是您想要的东西,请参阅 MapMaker.makeComputingMap。
Pretty sure guava has exactly what you are looking for, see MapMaker.makeComputingMap.
ConcurrentHashMap 中的代码是高度优化 - 我只会使用它。
如果更新很少,则并发开销很小。如果在读取期间发生写入操作,则在制作内部状态的临时副本时会产生一些开销,但否则性能差异可以忽略不计。我会按原样使用提供的类,只有当您发现遇到性能问题时,然后考虑使用其他东西。
请注意,初始化成本与并发性能无关,仅与将其添加到映射的操作相关。
The code in ConcurrentHashMap is highly optimized - I would just use it.
The concurrency overhead is minimal if there are few updates. If a write operation occurs during a read, there is some overhead when a temporary copy of the internal state is made, but otherwise the difference in performance in negligible. I would use the provided class as is and only if you find you are getting performance problems, then look into using something else.
Note that the initialization cost is not relevant to concurrency performance, only the operation of adding it to the map is.
这取决于您的要求,但您可以考虑使用实例池来减少实例化计数。如果您当前正在从地图中转储项目以进行垃圾收集,那么这将提高您的性能,因此您可以将它们放回池中并稍后重新使用,而不是进行 GC。
It depends on your requirements, but you may consider using a
Pool
of instances to reduce the instantiation count. That will improve your performance if you are currently dumping items from the map to garbage collect them, so instead of GC, you place them back in the pool and re-use them later.