Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Real alternatives to Clojure's concurrency primitives in Scala

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
like image 912
hawkeye Avatar asked Mar 22 '23 15:03

hawkeye


1 Answers

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.

like image 178
DaoWen Avatar answered Apr 06 '23 21:04

DaoWen