JohnDoDo
JohnDoDo

Reputation: 4900

Can I get iterators from an ArrayList in multiple threads and use all of them safelly?

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

Answers (2)

indika
indika

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:

  1. In multithreaded processing, if one thread is trying to modify a Collection while another thread is iterating over it.
  2. In single-threaded or in multithreaded, if after the creation of the Iterator, the collection is modified using its own methods rather using the Iterator's own methods.

Upvotes: 0

Martin Konecny
Martin Konecny

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

Related Questions