flash
flash

Reputation: 1229

ConcurrentHashMap Documentation clarification

ConcurrentHashMap is fully interoperable with Hashtable in programs that rely on its thread safety but not on its synchronization details.

I am confused with Thread Safety vs Synchronization details, can any one tell me an example?

Upvotes: 3

Views: 289

Answers (3)

alf
alf

Reputation: 8513

Hashtable has every method synchronized, and it's a publicly available information. For example, you can inherit from Hashtable, add more synchronized methods—and know you're doing mostly OK as you use the same synchronisation mechanism.

Moreover, your code can use synchronized (myHashTable) block, effectively ensuring no myHashTable methods are called from other threads while you're in this block.

That's all "synchronization details" which are available to you and which you are free (while discouraged) to use.

Not so with ConcurrentHashMap: it's as thread safe (and even more so in some sense, see e.g. the answer by Peter Lawrey) as Hashtable, but you're not told how this thread safety is achieved. As a result, you cannot abuse or extend it as you like: you're supposed to use it as it is.

Upvotes: 10

Peter Lawrey
Peter Lawrey

Reputation: 533442

A common thread safety got-cha is that the Iterator returned by iterator() method for the keySet(), entrySet() or values() are not thread safe for Hashtable, Vector, Collection.synchronizedXxxx(collection). While the method itself is thread safe, as soon as it returns an Iterator it could be invalid.

ConcurrentHashMap doesn't have this problem as its provides weak consistency. i.e. anything added, removed while Iterating may or may not be seen but otherwise entries appear as expect.

Upvotes: 2

Sunil Kumar Sahoo
Sunil Kumar Sahoo

Reputation: 53647

ConcurrentHashMap allows concurrent modification of the Map from several threads without the need to block them.

Have a look on tutorial on Synchronization and thread safety

Upvotes: 0

Related Questions