如何处理对Scala集合的并发访问? [英] How to handle concurrent access to a Scala collection?

查看:108
本文介绍了如何处理对Scala集合的并发访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Actor,从本质上讲,它维护着一个对象列表。它具有三个基本操作,即添加,更新和删除(有时从add方法中调用remove,但除此以外),并且与单个集合一起使用。显然,该后备列表是并发访问的,其中add和remove调用会不断地相互交织。

I have an Actor that - in its very essence - maintains a list of objects. It has three basic operations, an add, update and a remove (where sometimes the remove is called from the add method, but that aside), and works with a single collection. Obviously, that backing list is accessed concurrently, with add and remove calls interleaving each other constantly.

我的第一个版本使用了ListBuffer,但我在某处读到它并不意味着并发访问。我没有并发访问例外,但我确实注意到,发现&

My first version used a ListBuffer, but I read somewhere it's not meant for concurrent access. I haven't gotten concurrent access exceptions, but I did note that finding & removing objects from it does not always work, possibly due to concurrency.

我正在半途重写它以使用var List,但是从Scala的默认不可变列表中删除项目是一种有点痛苦-我怀疑它是否适合于并发访问。

I was halfway rewriting it to use a var List, but removing items from Scala's default immutable List is a bit of a pain - and I doubt it's suitable for concurrent access.

因此,基本问题是:在并发访问情况下应该使用哪种收集类型,以及如何使用它?

So, basic question: What collection type should I use in a concurrent access situation, and how is it used?

(也许是次要的:Actor实际上是多线程实体,还是我的错误观念,它是否在单个线程中一次处理一个消息? )

(Perhaps secondary: Is an Actor actually a multithreaded entity, or is that just my wrong conception and does it process messages one at a time in a single thread?)

(第三级:在Scala中,哪种集合类型最适合插入和随机访问(删除/更新)?)

(Tertiary: In Scala, what collection type is best for inserts and random access (delete / update)?)

编辑:对亲切的答复者:对不起我的最新答复,我正在养成一个讨厌的习惯,不是将问题转储到SO或邮件列表上,而是继续处理下一个问题,暂时忘记了原来的问题。

To the kind responders: Excuse my late reply, I'm making a nasty habit out of dumping a question on SO or mailing lists, then moving on to the next problem, forgetting the original one for the moment.

推荐答案

看看scala.collection.mut同步*特征/类。

Take a look at the scala.collection.mutable.Synchronized* traits/classes.

想法是将同步特征混入常规可变集合中,以获取它们的同步版本。

The idea is that you mixin the Synchronized traits into regular mutable collections to get synchronized versions of them.

例如:

import scala.collection.mutable._
val syncSet = new HashSet[Int] with SynchronizedSet[Int]
val syncArray = new ArrayBuffer[Int] with SynchronizedBuffer[Int]

这篇关于如何处理对Scala集合的并发访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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