Is the Scala List's cons-operator “::” thread-

2019-08-15 19:55发布

问题:

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

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

回答1:

To add to the answer that Jim Collins gave:

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

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.

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



回答2:

It is thread safe. In your example both threads would execute all the statements.