线程安全哈希映射?
我正在编写一个应用程序,它将返回一个 HashMap 给用户。用户将获得此地图的参考。 在后端,我将运行一些线程来更新地图。
到目前为止我做了什么?
我已经让所有后端线程共享一个公共通道来更新 MAP。因此,在后端,我确信并发写入操作不会成为问题。
我遇到的问题
- 如果用户尝试更新 MAP 并且同时 MAP 正在后端更新 -->并发写操作问题。
- 如果用户尝试从 MAP 读取某些内容,并且同时 MAP 正在后端更新 -->并发读和写操作问题。
到目前为止我还没有遇到过这样的问题,但我担心将来可能会遇到。请大家给点建议。
我正在使用 ConcurrentHashMap
I am writing an application which will return a HashMap to user. User will get reference to this MAP.
On the backend, I will be running some threads which will update the Map.
What I have done so far?
I have made all the backend threads so share a common channel to update the MAP. So at backend I am sure that concurrent write operation will not be an issue.
Issues I am having
- If user tries to update the MAP and simultaneously MAP is being updated at backend --> Concurrent write operation problem.
- If use tries to read something from MAP and simultaneously MAP is being updated at backend --> concurrent READ and WRITE Operation problem.
Untill now I have not face any such issue, but i m afraid that i may face in future. Please give sugesstions.
I am using ConcurrentHashMap<String, String>.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您使用
ConcurrentHashMap
。对于每个点:putIfAbsent
和replace
两者都是线程安全的,并且将检查 hashmap 的当前状态并将其更新为一个原子操作。ConcurrentHashMap 相对于
Collections.synchronizedMap
是像putIfAbsent
这样提供传统 Mapget
的组合方法> 并以内部同步的方式放置逻辑。使用这些方法,不要尝试通过ConcurrentHashMap
提供您自己的自定义同步,因为它不起作用。java.util.concurrent
集合在内部同步,其他线程不会响应同步对象的尝试(例如synchronize(myConcurrentHashMap){}
不会阻止其他线程) 。You are on the right track using
ConcurrentHashMap
. For each point:putIfAbsent
andreplace
both are threadsafe and combine checking current state of hashmap and updating it into one atomic operation.The benefit of
ConcurrentHashMap
over something likeCollections.synchronizedMap
is the combined methods likeputIfAbsent
which provide traditional Mapget
andput
logic in an internally synchronized way. Use these methods and do not try to provide your own custom synchronization overConcurrentHashMap
as it will not work. Thejava.util.concurrent
collections are internally synchronized and other threads will not respond to attempts at synchronizing the object (e.g.synchronize(myConcurrentHashMap){}
will not block other threads).旁注:
您可能想研究一下 Cliff Click 的无锁哈希表实现,它是 高度可扩展的 Java 库
(这是 Cliff Click 的 Google Talk 相关内容锁定自由散列。)
Side Note:
You might want to look into the lock free hash table implementation by Cliff Click, it's part of the Highly Scalable Java library
(Here's a Google Talk by Cliff Click about this lock free hash.)
ConcurrentHashMap 的设计和实现是为了避免您描述的场景出现任何问题。您无需担心。
javadoc并发HashMap
ConcurrentHashMap was designed and implemented to avoid any issues with the scenarios you describe. You have nothing to worry about.
javadoc of ConcurrentHashMap