Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is read operation in ConcurrentHashMap reliable regarding the return value?

I read in a book that read in ConcurrentHashmap does not guarantee the most recently updated state and it can sometimes gives the closer value. Is this correct?

I have read its javadocs and many blogs which seems to say otherwise (i.e. it is accurate).

Which one is true?

like image 700
N.. Avatar asked Nov 10 '22 06:11

N..


1 Answers

Intuitively, a ConcurrentHashMap should behave like a set of volatile variables; map keys being the variable addresses. get(key) and put(key, value) should behave like volatile read and write.

That is not explicitly stated in the document. However, I would strongly believe that it is the case. Otherwise there will be a lot of unexpected, surprising behaviors that undermine application logic. I don't think Doug Lea would do that to us. To be sure, someone please ask him on concurrency-interest mailing list.

Suppose it does obey the volatile semantics, we can reason based on Java Memory Model -

All volatile reads and writes form a single total order. This can be considered a pseudo time line, where reads/writes are points on it.

A volatile read sees the immediate preceding volatile write, and sees only that write. "Preceding" here is according to the pseudo time line.

The pseudo time line can differ from "real" time line. However, in theory, a volatile write cannot be infinitely postponed on the pseudo time line. And, in pracitce, two time lines are pretty close.

Therefore, we can be pretty sure that, a volatile write should become visible "very quickly" to reads.

like image 139
ZhongYu Avatar answered Nov 14 '22 22:11

ZhongYu