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

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

问题描述

我不知道这是否是同步的正确方法我的ArrayList

我有一个的ArrayList是从 registerInQueue in_queue C $ C>功能。

 的ArrayList<记录和GT; in_queue = NULL;公共无效registerInQueue(ArrayList的in_queue)
{
    this.in_queue = in_queue;
}

现在我想同步。这是我的sychronizing in_queue 对象是否正确?

 列表<记录和GT; in_queue_list = Collections.synchronizedList(in_queue);同步(in_queue_list){
    而(in_queue_list.size()大于0){
        in_queue_list.remove(0);
    }
}


解决方案

您正在同步两次,这是毫无意义的,并可能减慢了code:变化,同时遍历列表需要synchronnization在整个操作中,你与同步(in_queue_list)做使用 Col​​lections.synchronizedList()在这种情况下,多余的(它会创建一个包装,单个同步操作)。

然而,因为你完全清空列表,迭代拆除的第一个元素是最糟糕的方式做到这一点,SICE每个元素都下列元素都被复制,使之成为一个为O(n ^ 2)操作 - 对于较大的列表异常缓慢

相反,只需拨打清() - 没有迭代需要

编辑:
如果你需要 Col​​lections.synchronizedList的单一方法同步()以后,那么这是正确的方式:

 列表<记录和GT; in_queue_list = Collections.synchronizedList(in_queue);
in_queue_list.clear(); //隐式同步,

但是,在许多情况下,单方法同步是不足(例如,对于所有的迭代,或当得到一个值,执行基于它计算,并用结果替换它)。在这种情况下,你无论如何都要使用手动同步,所以 Col​​lections.synchronizedList()只是无用的额外开销。

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

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

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);
    }
}

解决方案

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

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.

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

Edit: 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,

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天全站免登陆