1

I have a List read (iterated through) many times and by multiple threads but updated rarely (reads are more than 50,000 times more numerous). EDIT: in fact, an array would suffice in this case, instead of a List.

When the list is updated, it's simply replaced with a different version (there are no add() or remove() calls).

A CopyOnWriteArrayList avoid the disadvantages of a synchronized list but I'm not sure that setting the list to the new value is atomic. I read this question as well.

To show some code. Consider the following as an attribute of a singleton Spring bean.

List<MyObject> myList; //the list read many times and concurrently. 

//called by many threads
public void doStuff(){           
     for (MyObject mo : myList){
         //do something
     }
}       

//called rarely. It's synchronized to prevent concurrent updates
//but my question is about thread-safety with regards to readers
public synchronized void updateList(List<MyObject> newList){  // newList is a CopyOnWriteArrayList<>(); 
    myList = myNewList;  //is this following statement executed atomically and thread-safe for readers?
}

Do I need to use a ReadWriteLock for achieve a thread-safe set?

1
  • 1
    I think it would suffice to make the list volatile... Commented Nov 20, 2014 at 2:07

1 Answer 1

1

The need for ReadWriteLock depends what you need to achieve. If you want to ensure that reference is updated atomically you can use AtomicReference (or in your case enough to mark this reference as volatile), however if your goal is that updater thread should wait until all reading threads finish iterating over old list before updating the reference then ReadWriteLock is the way to go.

Sign up to request clarification or add additional context in comments.

2 Comments

That's a good point about waiting for readers to finish. In my case, the list is short (<10 items) so with the projected load there will be a moment when all iterations are done and "it's quiet". This raises the interesting question about what to do if the list is long enough and the arrival rate high enough that new readers start iterating while others are finished, so there's always at least one iteration going on.
As I wrote it depends on use case. If you are fine that some threads are iterating over old list then go with volatile, however I can imagine several use cases when you want to be sure that once updated no one is using old list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.