4
votes

In Clojure I have four primitives to manage concurrency scenarios

  1. Refs - manage coordinated, synchronous changes to shared state
  2. Atoms - manage uncoordinated, synchronous changes to shared state
  3. Agents - manage asynchronous changes to shared state
  4. Vars - manage thread-local state

My questions is - is there a mature equivalent to each of these in Scala?

Assumptions - I'm going to assume that:

  • Actors are a different way to solve the problems that agents do - but they are no means a drop-in replacement
  • I'm aware there are agent libraries in Scala - I'm curious to know if they're considered mature
1
Scala vars do nothing to provide thread-safety. But then most good, functional Scala coders would tend to only use vars within contexts that safely encapsulated the mutable state, where they used them at all.itsbruce
@flavian Aren't those actor libraries? If so, see OP's first assumption.user395760

1 Answers

7
votes

Most of the concurrency constructs you listed for Clojure are based in software transactional memory. Because of that, I think you're basically just asking about STM support in Scala. According to the Akka documentation, the best choice for STM in Scala is ScalaSTM, and they say it's actually going to be included in the Scala Standard Library sometime in the future.

ScalaSTM supports Agents and Refs (which I believe were actually based on the Clojure versions). I think the corollary of an Atom would be the Ref.single type, which is just a ref that you can use outside of an atomic block.

Depending on your use case, a good substitute for var would be Java's ThreadLocal or Scala's DynamicVariable. Use ThreadLocal if all you want is thread-local data, but if you actually need dynamic binding, then I think you need DynamicVariable.