Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple threads accessing array

Tags:

java

android

I am trying to use arrayList across multiple threads in which 2 threads add elements to it and one thread just retrieve the first elements. I know I can use the syncronizedList but I wanted to see if this impleentation is right. Basically I add all my array manipulation in a synhcronized method

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

Is this ok?

like image 925
Snake Avatar asked Jan 17 '26 23:01

Snake


1 Answers

It is not enough to synchronize writing, you need to synchronize reading as well. Otherwise, a read that happens concurrently with a write may return inconsistent data, or trigger exceptions:

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

You could also use Collections.synchronizedList

List<String> syncList = Collections.synchronizedList(new ArrayList<String>());
like image 114
Sergey Kalinichenko Avatar answered Jan 20 '26 15:01

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!