Many readers, one writer: do I need to sync this?

Do I need to synchronize this when many threads accessing the get method and only one thread access the setList method?

public class ListContainer { private List<String> myList = new ArrayList<String(); public List<String> get ( ) { return new ArrayList<String>(myList); } public List<String> set ( ) { this.myList = computeList(); } } 

I don't like it if readers get old data, but the data should be consistent.

Janning

+4
source share
4 answers

You do not need to synchronize (but you must declare myList as volatile ) if the following conditions are true:

  • computeList does not depend on the current state of myList
  • You do not change the contents of the list after it is assigned ( Collections.unmodifiableList(computeList()) is the best way to express this condition)
+5
source

No, you do not need synchronization. There are no concurrent changes (if computeList() is independent of myList ).

btw, why are you returning new ArrayList(myList) instead of just returning myList ?

+1
source

It does not matter whether computeList depends on myList or not, if there is only read access to the contents of myList. No synchronization problem can occur.

If you do not use volatile for myList, then it may turn out that get returns the old myList, although a strictly installed one already replaced the list. If you do not mind this situation (this may lead to the two threads seeing different values), then you do not need variability.

0
source

I would rather make a copy of implicit

 public class ListContainer { private final List<String> myList = new CopyOnWriteArrayList<String>(); public List<String> get (){ return myList; } public List<String> set (){ computeList(); } } 

NTN

0
source

Source: https://habr.com/ru/post/1302051/


All Articles