I have ArrayLists that store many objects, and objects are frequently added and removed from the ArrayLists. One thread operates on the data structures and updates the ArrayList's objects every 20ms or so. Another thread traverses the ArrayLists and uses their elements to paint the objects (also every 20-30ms).
If the ArrayLists are traversed using a for loop, IndexOutOfBoundsExceptions abound. If the ArrayLists are traversed using iterators, ConcurrentModificationExceptions abound. Synchronizing the ArrayLists like so:
List list = Collections.synchronizedList(new ArrayList());
synchronized(list) {
//use iterator for traversals
}
Throws no exceptions but has a substantial performance drain. Is there a way to traverse these ArrayLists without exceptions being throw, and without a performance drain?
THANKS!
4. When two threads access the same ArrayList object what is the outcome of the program? Explanation: ArrayList is not synchronized. Vector is the synchronized data structure.
Implementation of ArrayList is not synchronized by default. It means if a thread modifies it structurally and multiple threads access it concurrently, it must be synchronized externally. Structural modification implies the addition or deletion of element(s) from the list or explicitly resizes the backing array.
Multiple threads accessing shared data simultaneously may lead to a timing dependent error known as data race condition. Data races may be hidden in the code without interfering or harming the program execution until the moment when threads are scheduled in a scenario (the condition) that break the program execution.
If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. Since there is no synchronization internally, what you theorize is not plausible.
A good approach to this problem is to make threads work on different copies of the list. However, CopyOnWriteArrayList
doesn't fit here well, since it creates a copy at every modification, but in your case it would be better to create copies less frequent.
So, you can implement it manually: the first thread creates a copy of the updated list and publishes it via the volatile
variable, the second thread works with this copy (I assume that the first thread modifies only list, not objects in it):
private volatile List publicList;
// Thread A
List originalList = ...;
while (true) {
modifyList(originalList); // Modify list
publicList = new ArrayList(originalList); // Pusblish a copy
}
// Thread B
while (true) {
for (Object o: publicList) { // Iterate over a published copy
...
}
}
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