I have the following executing sequentially in the one thread:
int size = hashTable.size();
foreach…. in … hasTable.values()
do something
My question will the foreach be executed size times ? (even if another thread puts/removes an element meanwhile ?
No,
HashTableis thread-safe on method level (multiple threads can call any method at any time) but there is no cross-method synchronization. It’s possible that between your two instructions other thread adds/removes or even clears the hashtable.If you need to keep such invariant, make a defensive copy (doesn’t have to be thread safe) and do
size()/loop on that copy:Here for-each is safe and it’s guaranteed to run size-times. Also as noted in comments, you can just synchronize on
hashTable:However this solution means that only one thread at a time can perform the loop (this can become a bottleneck if your loop takes some time to complete). With defensive copy each thread has its own copy and several threads can loop at the same time. On the other hand this solution is better if
hashTableis very big (expensive to copy) but the iteration is very fast.