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