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

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

问题描述

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



registerInQueue 函数传递的ArrayList in_queue

  ArrayList< Record> in_queue = null; 

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

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

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

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


解决方案

're同步两次,这是无意义的,可能会减慢代码:更改遍历列表需要同步整个操作,您正在使用 synchronized(in_queue_list)使用 Collections.synchronizedList()在这种情况下是多余的(它创建了一个同步单个操作的包装器)。



然而,由于你是完全清空列表,第一个元素的迭代删除是最糟糕的可能的方法来做,每个元素所有后面的元素必须被复制,使这是一个O(n ^ 2)操作 -



而是简单地调用 clear() - 不需要迭代。

编辑
如果您需要 Collections.synchronizedList()的单方法同步稍后,这是正确的方式:

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

但在许多情况下,单方法同步不够迭代,或当你得到一个值,做计算基于它,并用结果替换它)。在这种情况下,您必须使用手动同步,因此 Collections.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天全站免登陆