Reputation: 4900
I have an ArrayList instance that is shared by multiple threads. It's gets initialized in a synchronized block (so there is a memory barrier to make it visible to all threads) and all threads only read from it. The ArrayList never changes.
I've read lots of posts online but it's still not clear to me if it's safe to read no matter how I do the read. If I get an iterator from it in each thread do the iterators share some state that gets altered while iterating etc. I'm not sharing the iterators, each thread gets it's own.
Is it thread safe for reads, no matter how I do the read?
Upvotes: 2
Views: 1218
Reputation: 923
As long as iterators are used to read only this will work as expected.Also an iterator is fail-fast because it may throws a ConcurrentModificationException due to following reasons:
Upvotes: 0
Reputation: 59601
As long as each thread has its own iterator, then you are OK.
The only time you need to worry about synchronization is when one thread is modifying (writing) a shared data structure while others are reading from it. This can lead to the data-structure being in an inconsistent state (imagine the thread wasn't finished its modifications when all of a sudden the scheduler pre-empts it/switches to another thread).
When all threads are only reading, the data will never be in an inconsistent state, and you don't need to worry about thread synchronization.
Upvotes: 6