Reputation: 4600
So was just going through ConcurrentHashMap and it seems to be a threadsafe implementation with a fail-safe iterator.
The implementation of fail-safe iterators are created using copy of the data structures and hence this prevents the problem of Concurrent Modification would have introduced. But it adds a penalty of the added memory usage.
How high is this penalty? Is this always going to be equal to the size of the data structure?
Considering my plan to hold a lot of context in ConcurrentHashMap, it would really be detrimental for my application memory footprint to double suddenly if I iterate.
Also if there are 'n' threads iterating the data structure at the same time, is the memory penalty 'n' times the size of the data structure?
This seems to be a costly penalty to pay for Fail Safe iterators. If the penalty is off this order, can I prevent using the fail-safe iterators by combining fail-fast iterators with mutexes?
Upvotes: 0
Views: 162
Reputation: 198103
No, ConcurrentHashMap
's iterators don't make any copies like this. The worst-case scenario is that it retains a reference to a segment of the hash table longer than the map itself, but that reference will get GC'd as soon as the iterator is discarded or iterates past that segment of the map. The iterator itself takes O(1) memory, and O(1) time to create.
The iterator is weakly consistent, which means it is allowed but not obligated to reflect changes in the map since the iterator was created.
Upvotes: 4