本文介绍了线程安全哈希映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我正在编写一个应用程序,它将向用户返回一个HashMap。用户将获得对该MAP的参考。 在后端,我将运行一些线程来更新地图。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. 到目前为止我做了什么?我已经让所有后端线程共享一个公共通道来更新MAP。所以在后端我确信并发写入操作不会成为问题。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. 我遇到的问题 如果用户尝试更新MAP并同时更新MAP backend - >并发写操作问题。 如果使用尝试从MAP中读取某些内容,并且同时MAP正在后端更新 - >并发READ和WRITE Operation问题。现在我还没有遇到过这样的问题,但我担心我可能会面对未来。Untill now I have not face any such issue, but i m afraid that i may face in future. Please give sugesstions.我正在使用 ConcurrentHashMap< String,String>。推荐答案你在正确的轨道上使用 ConcurrentHashMap 。对于每一点:You are on the right track using ConcurrentHashMap. For each point: 查看方法 putIfAbsent 和 替换 都是线程安全的,并结合检查hashmap的当前状态并将其更新为一个原子操作。 get 方法在内部不同步,但会返回指定可用键的最新值(请查看 ConcurrentHashMap class Javadoc讨论)。Check out the methods putIfAbsent and replace both are threadsafe and combine checking current state of hashmap and updating it into one atomic operation.The get method is not synchronized internally but will return the most recent value for the specified key available to it (check the ConcurrentHashMap class Javadoc for discussion). ConcurrentHashMap 的优点超过了 Collections.synchronizedMap 是像 putIfAbsent 这样的组合方法,它们提供了传统的Map get 和以内部同步的方式放置逻辑。使用这些方法并且不要尝试通过 ConcurrentHashMap 提供自己的自定义同步,因为它不起作用。 java.util.concurrent 集合在内部同步,其他线程不会响应同步对象的尝试(例如 synchronize(myConcurrentHashMap){} / code>不会阻塞其他线程)。The benefit of ConcurrentHashMap over something like Collections.synchronizedMap is the combined methods like putIfAbsent which provide traditional Map get and put logic in an internally synchronized way. Use these methods and do not try to provide your own custom synchronization over ConcurrentHashMap as it will not work. The java.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). 这篇关于线程安全哈希映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-03 21:18
查看更多