Collections.synchronizedlist()从结束迭代时删除元素 [英] Collections.synchronizedlist() remove element while iterating from end

查看:877
本文介绍了Collections.synchronizedlist()从结束迭代时删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Collections.Synchronizedlist()来使我的 arraylist 线程安全。我想问的是以下代码线程安全,即从末尾迭代列表时删除: -

I am using Collections.Synchronizedlist() to make my arraylist thread safe. What I want to ask is the following code thread-safe i.e. remove while iterating over list from the end:-

pendingExecutionList = Collections.synchronizedList(new ArrayList<>(initialCapacity));

我在主线程中创建列表。并从不同的线程添加到此列表。但是,迭代和删除只能从一个Scheduled线程完成,如下所示: -

I am creating the list in main thread. and adding to this list from different threads. But, iteration and removal is being done only from a single Scheduled thread as shown below:-

for (int i = pendingExecutionList.size() - 1; i >= 0; i--) 
{
   if (someCondition(pendingExecutionList.get(i))) 
   {
      process(pendingExecutionList.remove(i));
   }
}

上述代码仅由一个线程执行多个线程正在添加到此列表中。

The above code is executed by only a single thread while multiple threads are adding to this list.

我想避免在 synchronized(list)上使用迭代器,因为这是不是故障安全的。

I want to avoid using iterator over synchronized(list) as that is not fail-safe.

推荐答案

如果我正确理解你的工作流程管道,我建议尝试一些<$的变体c $ c> BlockingQueue 而不是 synchronizedList()

If I'm understanding correctly your workflow pipeline, I would suggest trying some variant of a BlockingQueue instead of a synchronizedList().

ArrayBlockingQueue 将允许你公平地安排执行,并且应该保持多个生产者的缓存相当热(除非你的生产者开始超越缓存预取器,在这种情况下你会遇到错误分享)。

ArrayBlockingQueue would allow you to have fair scheduling of the executions and should keep the caches of the multiple producers fairly hot (unless your producers start overtaking the cache prefetcher, in which case you'll experience false sharing).

如果您有兴趣进行实验,可以查看JDK之外的MPSC(多个生产者,单个消费者)队列,如Nitsan Wakart的 MpscArrayQueue 干扰者

If you are in the mood for experimenting, you can take a look at the MPSC (multiple producers, single consumer) queues available outside of the JDK, like Nitsan Wakart's MpscArrayQueue or the Disruptor.

这篇关于Collections.synchronizedlist()从结束迭代时删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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