两个线程访问频繁更新的 Arraylist 的问题 [英] Problems with two threads accessing a frequently updated Arraylist

查看:21
本文介绍了两个线程访问频繁更新的 Arraylist 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有存储许多对象的 ArrayList,并且经常在 ArrayList 中添加和删除对象.一个线程对数据结构进行操作并每 20 毫秒左右更新一次 ArrayList 的对象.另一个线程遍历 ArrayLists 并使用它们的元素来绘制对象(也是每 20-30 毫秒).

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).

如果使用 for 循环遍历 ArrayLists,IndexOutOfBoundsExceptions 比比皆是.如果使用迭代器遍历 ArrayList,则 ConcurrentModificationExceptions 比比皆是.像这样同步 ArrayList:

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
}

不会引发任何异常,但会显着降低性能.有没有办法遍历这些 ArrayList 而不会抛出异常,并且不会降低性能?

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?

谢谢!

推荐答案

解决这个问题的一个好方法是让线程在列表的不同副本上工作.但是,CopyOnWriteArrayList 不适合这里,因为它在每次修改时都会创建一个副本,但在您的情况下,最好减少创建副本的频率.

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.

因此,您可以手动实现它:第一个线程创建更新列表的副本并通过 volatile 变量发布它,第二个线程使用此副本(我假设第一个线程只修改列表,不修改其中的对象):

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
        ...
    }
}

这篇关于两个线程访问频繁更新的 Arraylist 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆