在java中同步ArrayList的正确方法 [英] Correct way to synchronize ArrayList in java

查看:39
本文介绍了在java中同步ArrayList的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定这是否是同步我的 ArrayList 的正确方法.

I'm not sure if this is the correct way to synchronize my ArrayList.

我有一个从 registerInQueue 函数传入的 ArrayList in_queue.

I have an ArrayList in_queue which is passed in from the registerInQueue function.

ArrayList<Record> in_queue = null;

public void registerInQueue(ArrayList in_queue)
{
    this.in_queue = in_queue;
}

现在我正在尝试同步它.这是否正确同步了我的 in_queue 对象?

Now I'm trying to synchronize it. Is this sychronizing my in_queue object correctly?

List<Record> in_queue_list = Collections.synchronizedList(in_queue);

synchronized (in_queue_list) {
    while (in_queue_list.size() > 0) {
        in_queue_list.remove(0);
    }
}

推荐答案

您要同步两次,这是毫无意义的,并且可能会减慢代码速度:迭代列表时的更改需要对整个操作进行同步,而您正在同步使用 synchronized (in_queue_list) 在这种情况下使用 Collections.synchronizedList() 是多余的(它创建了一个同步各个操作的包装器).

You're synchronizing twice, which is pointless and possibly slows down the code: changes while iterating over the list need a synchronnization over the entire operation, which you are doing with synchronized (in_queue_list) Using Collections.synchronizedList() is superfluous in that case (it creates a wrapper that synchronizes individual operations).

但是,由于您要完全清空列表,因此迭代删除第一个元素是最糟糕的方法,必须复制每个元素的所有后续元素,使其成为 O(n^2)操作 - 对于较大的列表,速度非常慢.

However, since you are emptying the list completely, the iterated removal of the first element is the worst possible way to do it, sice for each element all following elements have to be copied, making this an O(n^2) operation - horribly slow for larger lists.

相反,只需调用 clear() - 不需要迭代.

Instead, simply call clear() - no iteration needed.

如果以后需要Collections.synchronizedList()的单方法同步,那么正确的做法是:

If you need the single-method synchronization of Collections.synchronizedList() later on, then this is the correct way:

List<Record> in_queue_list = Collections.synchronizedList(in_queue);
in_queue_list.clear(); // synchronized implicitly, 

但是在很多情况下,单方法同步是不够的(例如对于所有迭代,或者当你得到一个值时,根据它做计算,并用结果替换它).在这种情况下,您无论如何都必须使用手动同步,因此 Collections.synchronizedList() 只是无用的额外开销.

But in many cases, the single-method synchronization is insufficient (e.g. for all iteration, or when you get a value, do computations based on it, and replace it with the result). In that case, you have to use manual synchronization anyway, so Collections.synchronizedList() is just useless additional overhead.

这篇关于在java中同步ArrayList的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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