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?
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>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With