lowLatency
lowLatency

Reputation: 5664

ConcurrentHashMap retrieval operation does not take lock?

as per Java docs

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

question : Suppose a thread t1 is updating a key-value pair(called x), and then other thread t2 comes and want to read x, will there be a copy c1 created of x at the onset of t2 and t2 will read from that copy c1

Upvotes: 2

Views: 424

Answers (2)

goblinjuice
goblinjuice

Reputation: 3214

question : Suppose a thread t1 is updating a key-value pair(called x), and then other thread t2 comes and want to read x, will there be a copy c1 created of x at the onset of t2 and t2 will read from that copy c1

It depends. If the operation by T1 is complete, T2 will see that value. Otherwise, T2 will see the old value.

From http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html:

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

Upvotes: 1

M Sach
M Sach

Reputation: 34424

Retrievals reflect the results of the most recently completed update operations holding upon their onset

completed word is important here. Now your scenario is

 Suppose a thread t1 is updating a key-value pair(called x), and then other thread t2 comes and want to read x.

T2 will read value updated by operation which has been completed not under process.In your scenario if update operation by thread t1 is not complete, t2 will not see the updated value. No copy is created. Its simple time funda. If by the time t2 thread read the x value and t2 update operation is complete, it will see the updated value otherwise not.

Upvotes: 1

Related Questions