Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple threads iterating over the same map

I was recently writing a concurrent program in Java and came across the dollowing dilemma: suppose you have a global data structure, which is partof regular non-synchronized, non-concurrent lib such as HashMap. Is it OK to allow multiple threads to iterate through the collection (just reading, no modifications) perhaps at different, interleaved periods i.e. thread1 might be half way thrpugh iterating when thread2 gets his iterator on the same map?

like image 990
Bober02 Avatar asked Mar 08 '12 10:03

Bober02


1 Answers

It is OK. Ability to do this is the reason to create such interface as iterator. Every thread iterating over collection has its own instance of iterator that holds its state (e.g. where you are now in your iterating process).

This allows several threads to iterate over the same collection simultaneously.

like image 139
AlexR Avatar answered Sep 20 '22 01:09

AlexR