java同步list,在java中正确同步ArrayList的方法

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值