问题描述
我正在阅读有关 Java 并发的官方 Oracle 文档,我想知道由
I was reading the official Oracle documentation about Concurrency in Java and I was wondering what could be the difference between a Collection
returned by
public static <T> Collection<T> synchronizedCollection(Collection<T> c);
并使用例如
ConcurrentHashMap
.我假设我在 HashMap
上使用 synchronizedCollection(Collection<T> c)
.我知道一般来说,同步集合本质上只是我的 HashMap
的装饰器,因此很明显 ConcurrentHashMap
在其内部有一些不同的东西.你有关于这些实施细节的一些信息吗?
ConcurrentHashMap
. I'm assuming that I use synchronizedCollection(Collection<T> c)
on a HashMap
. I know that in general a synchronized collection is essentially just a decorator for my HashMap
so it is obvious that a ConcurrentHashMap
has something different in its internals. Do you have some information about those implementation details?
我意识到源代码是公开的:ConcurrentHashMap.java
推荐答案
我会阅读 ConcurrentHashMap的来源,因为它在细节上相当复杂.简而言之,它有
I would read the source of ConcurrentHashMap as it is rather complicated in the detail. In short it has
- 可以独立锁定的多个分区.(默认 16 个)
- 使用并发锁操作来保证线程安全,而不是同步.
- 具有线程安全的迭代器.synchronizedCollection 的迭代器不是线程安全的.
- 不暴露内部锁.synchronizedCollection 可以.
这篇关于ConcurrentHashMap 如何在内部工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!