Multiple threads accessing an array

I am trying to use arrayList for multiple threads, in which 2 threads add elements to it, and one thread just extracts the first elements. I know that I can use syncronizedList, but I wanted to see if this incarnation is correct. Basically I add all array manipulations in a synchronous method

public void synchronized addElem(String str){
  String s = str.trim();
  myArray.add(s);
 }

This is normal?

+3
source share
3 answers

It is not enough to synchronize the record, you also need to synchronize the reading. Otherwise, a read that occurs concurrently with the write may return inconsistent data or throw exceptions:

public synchronized String getFirst() {
    if (myArray.size() != 0)
        return myArray.get(0);
    return null;
}

You can also use Collections.synchronizedList

List<String> syncList = Collections.synchronizedList(new ArrayList<String>());
+5
source

. , , , . , . , .

+3

You can also use a synchronized block like synchronized(myArray) { // logic}. This is preferred over the synchronous method if your method is too long and too long to hold the required object. On the other hand, a block synchronizedwill block an object only as long as it is needed.

+2
source

All Articles