Atomic Counters in Scala
Our primary mechanism for managing state in Scala is often through immutable data structures and functional programming patterns. However, there are scenarios where we need to manage shared mutable state across multiple threads. In this example, we’ll look at using atomic variables for thread-safe counters.
We expect to get exactly 50,000 operations. Had we used a non-atomic integer and incremented it with regular addition, we’d likely get a different number, changing between runs, because the threads would interfere with each other.
To run the program:
In this Scala version:
We use
AtomicLong
fromjava.util.concurrent.atomic
package, which provides atomic operations onlong
values.Instead of goroutines, we use Scala’s
Future
s to represent concurrent computations.We use a
for
comprehension to create 50 futures, each incrementing the counter 1000 times.Future.sequence
is used to convert our sequence of futures into a future of sequence, which we then wait for usingAwait.result
.The
incrementAndGet()
method atomically increments the counter and returns the new value, similar to theAdd
method in the Go version.Finally, we use
get()
to retrieve the final value of the counter.
This example demonstrates how to use atomic variables for thread-safe operations in Scala, providing similar functionality to the atomic counters in the original Go example.