Atomic Counters in Kotlin
In Kotlin, we can use atomic operations for managing state across multiple coroutines. Let’s look at using the java.util.concurrent.atomic
package for atomic counters accessed by multiple coroutines.
Let’s break down the key components:
We use
AtomicLong
fromjava.util.concurrent.atomic
package to represent our counter.Instead of Go’s WaitGroup, we use Kotlin’s structured concurrency with
coroutineScope
andlaunch
.We create 50 coroutines using
List(50)
andlaunch
, each incrementing the counter 1000 times.The
incrementAndGet()
method is used to atomically increment the counter.We wait for all coroutines to complete using
jobs.forEach { it.join() }
.Finally, we safely read the final value using
ops.get()
.
To run this program:
We expect to get exactly 50,000 operations. If we had used a non-atomic integer and incremented it with ++
, we’d likely get a different number, changing between runs, because the coroutines would interfere with each other.
Next, we’ll look at mutexes, another tool for managing state in concurrent programs.