我正试图找到这些问题的答案,但无法在 Google 或 Java 文档中找到。
情况 1: 在 ConcurrentHashMap
中,假设一个线程 t1 正在从段 n 中读取,并且同时另一个线程 t2 想在 同一个段 n 上写:
问题1:这两个操作是依次执行还是同时执行?
情况 2:在 ConcurrentHashMap
中,假设一个线程 t1 正在写入段 n,同时另一个线程 < em>t2 想从同一个段 n 读取,
问题二:这两个操作是依次执行还是同时执行?
最佳答案
我认为 javadoc 回答了您的两个问题:
Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries.
段用于更新操作:
The allowed concurrency among update operations is guided by the optional concurrencyLevel constructor argument (default 16), which is used as a hint for internal sizing.
所以,简而言之,读取没有被阻塞(它被实现为读取volatile变量)。如果写入同一段,则写入可能会相互阻塞。
关于java - ConcurrentHashMap读写锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16105554/