简体   繁体   English

ConcurrentHashMap 使用

[英]ConcurrentHashMap usage


Another question today.今天还有一个问题。

I am trying to understand if I should use a ConcurrentHashMap for one of my service or not.我试图了解是否应该将 ConcurrentHashMap 用于我的一项服务。

I have a service DataService that fetches data every 10sec from a database and puts it in a map dataMap = Map<Key,Data>我有一个服务DataService ,它每 10 秒从数据库中获取数据并将其放入 map dataMap = Map<Key,Data>
This service is scheduled on a different thread than my main thread.该服务安排在与我的主线程不同的线程上。

In my main thread, every now and then i have to get an element from the map dataMap在我的主线程中,我时不时地必须从dataMap中获取一个元素
The main thread only use get and never updates the map.主线程只使用get而从不更新 map。

My question, does the dataMap have to be a ConcurrentHashMap in this case?我的问题,在这种情况下, dataMap必须是 ConcurrentHashMap 吗?

Thanks谢谢

You have to address the reader and writer accessing the map concurrently.您必须解决同时访问 map 的读写器。 Specifically, a HashMap is not sufficient.具体来说,HashMap 是不够的。 From the JavaDoc:来自 JavaDoc:

"Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings." “注意,这个实现是不同步的。如果多个线程同时访问一个hash map,并且至少有一个线程修改了map在结构上,它必须是在结构上同步或删除的任何操作。映射。”

Adding a new map entry from the database is a structural modification and may result in a ConcurrentModificationException.从数据库中添加新的 map 条目是一种结构修改,可能会导致 ConcurrentModificationException。

Note that ConcurrentHashMap is still very efficient.请注意,ConcurrentHashMap 仍然非常有效。 From the Javadoc:来自 Javadoc:

"A hash table supporting full concurrency of retrievals and high expected concurrency for updates. .... Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove)." “支持检索的完全并发和更新的高预期并发性的 hash 表......检索操作(包括获取)通常不会阻塞,因此可能与更新操作(包括放置和删除)重叠。”

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

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