Reputation: 14658
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?
Upvotes: 3
Views: 154
Reputation: 25018
You can also used a synchronized block as synchronized(myArray) { // logic}
. This is preferred over a synchronized method if your method is too long and will hold up the required object for too long. synchronized
block, on the other hand, will keep the object locked only as long as it is needed.
Upvotes: 2
Reputation: 93668
No. You'd need to synchronize on ALL times you access the list, as well as make sure you don't pass any references to it elsewhere. That's why the synchronized classes exist- to save you the effort. This is part of the answer, but not sufficient.
Upvotes: 3
Reputation: 726809
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>());
Upvotes: 5