Java – Multithreaded access to arrays

Multithreaded access to arrays… here is a solution to the problem.

Multithreaded access to arrays

I’m trying to use arrayList across multiple threads where 2 threads add elements to it and one thread retrieves only the first element. I know I can use syncronizedList, but I’d like to see if this implementation is correct. Basically I added all my array operations in one synchronous method

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

Is this okay?

Solution

Write synchronization is not enough, read synchronization is also required. Otherwise, reads that occur at the same time as the write may return inconsistent data, or trigger an exception:

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>());

Related Problems and Solutions