Anand
Anand

Reputation: 21358

Iteration of ConcurrentHashMap

I was reading about ConcurrentHashMap.

I read that it provides an Iterator that requires no synchronization and even allows the Map to be modified during iteration and thus there will be no ConcurrentModificationException.

I was wondering if this is a good thing as I might not get the element, put into ConcurrentHashMap earlier, during iteration as another thread might have changed it.

Is my thinking correct? If yes, is it good or bad?

Upvotes: 3

Views: 510

Answers (3)

Zim-Zam O'Pootertoot
Zim-Zam O'Pootertoot

Reputation: 18158

Usually, the ConcurrentHashMap weakly consistent iterator is sufficient. If instead you want a strongly consistent iterator, then you have a couple of options:

  1. The ctrie is a hash array mapped trie that provides constant time snapshots. There is Java source code available for the data structure.
  2. Clojure has a PersistentHashMap that you can use - this lets you iterate over a snapshot of the data.
  3. Use a local database, e.g. HSQLDB to store the data instead of using a ConcurrentHashMap. Use a composite primary key of key|timestamp, and when you "update" a value you instead store a new entry with the current timestamp. To get an iterator, retrieve a resultset with a where timetamp < System.currentTimeMillis() clause, and iterate over the resultset.

In either case you're iterating over a snapshot, so you've got a strongly consistent iterator; in the former case you run the risk of running out of memory, while the latter case is a more complex solution.

Upvotes: 1

Dilum Ranatunga
Dilum Ranatunga

Reputation: 13374

The whole point of concurrent -anything is that you acknowledge concurrent activity, and don't trust that all access is serialized. With most collections, you cannot expect inter-element consistency without working for it.

If you don't care about seeing the latest data, but want a consistent (but possibly old) view of data, have a look at purely functional structures like Finger Trees.

Upvotes: 0

matt b
matt b

Reputation: 140061

I was wondering if this is a good thing as I might not get the element, put into ConcurrentHashMap earlier, during iteration as another thread might have changed it.

I don't think this should be a concern - the same statement is true if you use synchronization and the thread doing the iteration happens to grab the lock and execute it's loop prior to the thread that would insert the value.

If you need some sort of coordination between your threads to ensure that some action takes place after (and only after) another action, then you still need to manage this coordination, regardless of the type of Map used.

Upvotes: 4

Related Questions