java - Is iterating ConcurrentHashMap values thread safe? -


in javadoc concurrenthashmap following:

retrieval operations (including get) not block, may overlap update operations (including put , remove). retrievals reflect results of completed update operations holding upon onset. aggregate operations such putall , clear, concurrent retrievals may reflect insertion or removal of entries. similarly, iterators , enumerations return elements reflecting state of hash table @ point @ or since creation of iterator/enumeration. not throw concurrentmodificationexception. however, iterators designed used 1 thread @ time.

what mean? happens if try iterate map 2 threads @ same time? happens if put or remove value map while iterating it?

what mean?

that means each iterator obtain concurrenthashmap designed used single thread , should not passed around. includes syntactic sugar for-each loop provides.

what happens if try iterate map 2 threads @ same time?

it work expected if each of threads uses it's own iterator.

what happens if put or remove value map while iterating it?

it guaranteed things not break if (that's part of "concurrent" in concurrenthashmap means). however, there no guarantee 1 thread see changes map other thread performs (without obtaining new iterator map). iterator guaranteed reflect state of map @ time of it's creation. futher changes may reflected in iterator, not have be.

in conclusion, statement like

for (object o : someconcurrenthashmap.entryset()) {     // ... } 

will fine (or @ least safe) every time see it.


Comments

Popular posts from this blog

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

c++ - Convert big endian to little endian when reading from a binary file -

openssl - Load PKCS#8 binary key into Ruby -