thread safety - Java ConcurrentHashMap and For Each Loop -
supposed have following concurrenthashmap:
concurrenthashmap<integer,string> indentificationdocuments = new concurrenthashmap<integer,string>(); indentificationdocuments.put(1, "passport"); indentificationdocuments.put(2, "driver's licence"); how safely iterate on map each loop , append value of each entry string?
iterators produced concurrenthashmap weakly consistent. is:
- they may proceed concurrently other operations
- they never throw concurrentmodificationexception
- they guaranteed traverse elements existed upon construction once, , may (but not guaranteed to) reflect modifications subsequent construction.
the last bullet-point pretty important, iterator returns view of map @ point since creation of iterator, quote different section of javadocs concurrenthashmap:
similarly, iterators, spliterators , enumerations return elements reflecting state of hash table @ point @ or since creation of iterator/enumeration.
so when loop through keyset following, need double check if item still exists in collection:
for(integer i: indentificationdocuments.keyset()){ // below line problem, get(i) may not exist anymore may still in view of iterator // somestringbuilder.append(indentificationdocuments.get(i)); // next line work somestringbuilder.append(identificationdocuments.getordefault(i, "")); } the act of appending strings stringbuilder safe, long doing on 1 thread or have encapsulated stringbuilder entirely in thread-safe manner.
Comments
Post a Comment