I have several data listeners, which may receive datasets roughly at the same time. They will iterate datasets and store data to the same ArrayList by using its method add(). Could this potentially cause any issues of some data items not being stored?
2 Answers
ArrayList is not synchronized. From the docs
Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.)
You can use synchronizedList for this
List list = Collections.synchronizedList(new ArrayList(...));
Comments
You can use synchronized block in this case :
synchronized (this){
// ...
}
You can find a good examples here Synchronized
ArrayList'is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally.'.