是 Scala List 的 cons-operator “::"吗?线程安全? [英] Is the Scala List's cons-operator "::" thread-safe?

查看:89
本文介绍了是 Scala List 的 cons-operator “::"吗?线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在给定列表中的 cons-operator :: 是线程安全的吗?

Is the cons-operator :: on a given list thread-safe?

例如,如果 2 个线程使用同一个列表中的 cons-operator 会发生什么?

For example what happens if 2 threads use the cons-operator on the same list?

val listOne = 1::2::3::Nil
val listTwo = 4::5::Nil
val combinedList = listOne ::: listTwo  // thread1
val combinedList2 = listOne ::: 7:8:NIL // thread2 on the same time

推荐答案

补充一下 Jim Collins 给出的答案:

To add to the answer that Jim Collins gave:

对不可变数据结构的所有操作通常都是线程安全的.list cons 运算符不会修改原始列表,因为每个列表都是不可变的.相反,它会创建一个新列表来表示列表的更改状态.

All operations on immutable data structures are generally thread safe. The list cons operator does not modify the original list, since every list is immutable. Instead, it creates a new list that represents the changed state of the list.

线程同步问题仅在不同线程想要更​​改内存中的相同数据时出现.这个问题被称为共享状态".不可变对象是无状态的,因此不能有共享状态.

Thread synchronization issues only arise when different threads want to change the same data in memory. This problem is called "shared state". Immutable objects are stateless, therefore there can be no shared state.

Scala 还提供可变数据结构.注意包名称中的可变"一词.那些与 Java 集合具有相同的同步问题.

Scala also offers mutable data structures. Look out of the term "mutable" in the package name. Those have all the same synchronization issues as Java collections have.

默认情况下,如果您只在 Scala 程序中键入 List,而不添加任何特殊的 import 语句,Scala 将使用不可变列表.SetMap 等也是如此.

By default, if you just type List inside a Scala program, without adding any special import statements, Scala will use an immutable list. The same goes for Set, Map, etc.

经验法则:如果一个类不包含 var 语句,并且没有引用任何其他包含 var 语句的类,则可以认为它是不可变的.这意味着它可以安全地在线程之间传递.(我知道专家可以很容易地从这条规则中构建例外,但只要你一无所知,这是一个很好的规则,边缘情况放在一边.)

Rule of thumb: If a class does not contain a var statement, and no reference to any other class that contains a var statement, it can be regarded as immutable. That means it can be passed between threads safely. (I know that experts can easily construct exceptions from this rule, but as long as you know nothing else, this is a pretty good rule to go by, edge cases set aside.)

这篇关于是 Scala List 的 cons-operator “::"吗?线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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