user6014500
user6014500

Reputation:

ConcurrentHashMap Iteration

ConcurrentHashMap is thread-safe , so we can update value of map at the time of iteration . but output of below program is not as i expected.

Map concurrentHashMap = new ConcurrentHashMap<();
concurrentHashMap.put("0", "b");
Iterator iterator = concurrentHashMap.entrySet().iterator();
concurrentHashMap.put("8", "k");
concurrentHashMap.put("2", "c");
concurrentHashMap.put("3", "d");
concurrentHashMap.put("1", "e");        
    
while(iterator.hasNext())
{
    System.out.println(""+iterator.next());
}

output of above code is

0=b

8=k

3=d

2=c

expected output

1=e

0=b

8=k

3=d

2=c

Upvotes: 0

Views: 139

Answers (1)

Sean Bright
Sean Bright

Reputation: 120714

From the documentation for ConcurrentHashMap.entrySet():

The view's iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

Upvotes: 1

Related Questions