ConcurrentHashMap usage

huangapple go评论71阅读模式
英文:

ConcurrentHashMap usage

问题

<br>

今天又有一个问题。<br>

我正在尝试理解是否应该在我的一个服务中使用ConcurrentHashMap。<br>

我有一个名为DataService的服务,它每10秒从数据库中获取数据并将其放入一个名为dataMap = Map&lt;Key,Data&gt;的映射中。<br>
这个服务在与我的主线程不同的线程上调度。

在我的主线程中,不时需要从映射dataMap中获取一个元素。<br>
主线程只使用get,从不更新映射。

我的问题是,在这种情况下,dataMap是否必须是ConcurrentHashMap?

谢谢

英文:

<br>

Another question today.<br>

I am trying to understand if I should use a ConcurrentHashMap for one of my service or not.<br>

I have a service DataService that fetches data every 10sec from a database and puts it in a map dataMap = Map&lt;Key,Data&gt; <br>
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<br>
The main thread only use get and never updates the map.

My question, does the dataMap have to be a ConcurrentHashMap in this case?

Thanks

答案1

得分: 1

你必须处理同时访问地图的读取器和写入器。具体来说,HashMap 不足以满足需求。根据 JavaDoc:

“请注意,此实现未同步。如果多个线程同时访问哈希映射,并且至少有一个线程在结构上修改了映射,则必须在外部进行同步。(结构上的修改是指添加或删除一个或多个映射的任何操作。"

从数据库添加新的映射条目是一种结构性修改,可能导致 ConcurrentModificationException 异常。

请注意,ConcurrentHashMap 仍然非常高效。根据 Javadoc:

“支持检索的完全并发性和更新的高度预期并发性的哈希表...检索操作(包括 get)通常不会阻塞,因此可以与更新操作(包括 put 和 remove)重叠进行。”

英文:

You have to address the reader and writer accessing the map concurrently. Specifically, a HashMap is not sufficient. From the 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."

Adding a new map entry from the database is a structural modification and may result in a ConcurrentModificationException.

Note that ConcurrentHashMap is still very efficient. From the 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)."

huangapple
  • 本文由 发表于 2020年8月8日 01:15:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63306476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定