Problems with two threads accessing the frequently updated Arraylist

I have ArrayLists that store many objects, and objects are often added and removed from ArrayLists. One thread works with data structures and updates ArrayList objects every 20 ms or so. Another thread traverses ArrayLists and uses their elements to draw objects (also every 20-30 ms).

If ArrayLists are passed using a for loop, there is an IndexOutOfBoundsExceptions value. If the intersection of ArrayLists is done using iterators, then there are many in ConcurrentModificationExceptions. Array synchronization like:


List list = Collections.synchronizedList(new ArrayList());
synchronized(list) {
//use iterator for traversals
}

Does not exclude exceptions, but has a significant loss in performance. Is there a way to traverse these ArrayLists without throwing exceptions, and without losing performance?

THANK!

+5
source share
6 answers

A good approach to this problem is to create threads for different copies of the list. However CopyOnWriteArrayList, it is not suitable here, since it creates a copy with each modification, but in your case it would be better to create copies less often.

So, you can implement it manually: the first thread creates a copy of the updated list and publishes it using a variable volatile, the second thread works with this copy (I assume that the first thread changes only the list, not the 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
        ...
    }
}
+4
source

Iterator CopyOnWriteArrayList? ConcurrentModificationException s.

javadocs Oracle ( ):

ArrayList (, ..) .

, , , , . " " , . , ConcurrentModificationException. , , . , (, add) . throw UnsupportedOperationException.

+2

ArrayList ? , .

+2

CopyOnWriteArrayList, ConcurrentModificationException, , - .

List list = Collections.synchronizedList(new ArrayList());

List copy;
// lock the list for the minimal amount of time.
synchronized(list) {
    copy = new ArrayList(list);
}
// use the copy of the array list.

BTW CopyOnWriteArrayList

List list = new CopyOnWriteArrayList();

// use the list.
+1

CopyOnWriteArrayList , , .

, , , , ConcurrentLinkedQueue. . JAVA: Concurrency java.

+1

All Articles