我不是这方面的专家,但在ConcurrentHashMap
望着Segment
实施我看到volatile
场count
似乎被用来确保线程之间的正确可见性所有读取操作必须读取count
字段,所有写入操作必须写入该字段。从类注释:
Read operations can thus proceed without locking, but rely
on selected uses of volatiles to ensure that completed
write operations performed by other threads are
noticed. For most purposes, the "count" field, tracking the
number of elements, serves as that volatile variable
ensuring visibility. This is convenient because this field
needs to be read in many read operations anyway:
- All (unsynchronized) read operations must first read the
"count" field, and should not look at table entries if
it is 0.
- All (synchronized) write operations should write to
the "count" field after structurally changing any bin.
The operations must not take any action that could even
momentarily cause a concurrent read operation to see
inconsistent data. This is made easier by the nature of
the read operations in Map. For example, no operation
can reveal that the table has grown but the threshold
has not yet been updated, so there are no atomicity
requirements for this with respect to reads.
所以,如果我理解正确没有问题,就像在经典的双重检查锁定范例? – GorillaApe 2011-05-13 20:36:18
@Parhs:对,没有问题。 – ColinD 2011-05-13 20:45:32
你是对的。你实际上在'你的问题中自己回答了'但是不稳定可以解决1中的问题。5 +'由于从CCHM返回的值是一个易失值,因此它也可以安全地进行部分初始化。 – 2011-05-13 20:45:47