简体   繁体   English

ConcurrentHashMap操作

[英]ConcurrentHashMap operations

Following are some lines from the java docs of ConcurrentHashMap 以下是ConcurrentHashMap的Java文档中的一些内容

This class obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable. 此类遵循与Hashtable相同的功能规范,并且包括与Hashtable的每个方法相对应的方法的版本。 However, even though all operations are thread-safe, retrieval operations do not entail locking, and there is not any support for locking the entire table in a way that prevents all access. 但是,即使所有操作都是线程安全的,检索操作也不需要进行锁定,并且不支持以阻止所有访问的方式锁定整个表。

What is the meaning of the statement 声明的含义是什么

though all operations are thread-safe 尽管所有操作都是线程安全的

from above paragraph? 从上一段开始? Can anyone explain with any example of put() or get() methods? 任何人都可以用put()或get()方法的任何示例进行解释吗?

The ConcurrentHashMap allows concurrent modification of the Map from several threads without the need to block them. ConcurrentHashMap允许从多个线程并发修改Map,而无需阻止它们。 Collections.synchronizedMap(map) creates a blocking Map which will degrade performance, albeit ensure consistency (if used properly). Collections.synchronizedMap(map)创建一个阻塞Map,这会降低性能,尽管可以确保一致性(如果使用正确)。

Use the second option if you need to ensure data consistency, and each thread needs to have an up-to-date view of the map. 如果需要确保数据一致性,并且每个线程都需要具有最新的地图视图,请使用第二个选项。 Use the first if performance is critical, and each thread only inserts data to the map, with reads happening less frequently. 如果性能至关重要,请使用第一个,并且每个线程仅将数据插入到映射中,而读取的频率则较低。

Your question is odd. 您的问题很奇怪。 If you understand what "thread safety" means then you would be able to understand how it applies to get() and put() on your own. 如果您了解“线程安全性”的含义,那么您将能够自己理解它如何应用于get()和put()。 If you don't understand thread safety then there is no point to explain it specifically in relation to get() and put(). 如果您不了解线程安全性,那么就没有必要专门针对get()和put()对其进行解释。 Are you sure this isn't a homework question? 您确定这不是作业问题吗?

However, answering your question anyway, the fact that ConcurrentHashMap is thread safe means that if you have several threads executing put()s on the same map at the same time, then: a) no damage will occur to the internal data structures of the map and: b) some other thread doing a get() will see all of the values put in by the other threads. 但是,无论如何回答您的问题,ConcurrentHashMap是线程安全的事实意味着,如果您有多个线程同时在同一张图上执行put(),那么:a)不会损坏该对象的内部数据结构map和:b)其他执行get()的线程将看到其他线程输入的所有值。 With a non-thread safe Map such as HashMap neither of those are guaranteed. 对于非线程安全的Map(例如HashMap),不能保证所有这些。

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

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