During this chapter, we have covered how to write our own atomic blocks of code, but there's yet another topic that we need to mention regarding atomicity: atomic data structures. These are data structures that offer atomic operations out of the box.
Currently these atomic data structures are provided by the JVM, not Kotlin's standard library. So they may not be available if your code is for JS, Kotlin/Native, or multiplatform.
For example, using an atomic integer looks like the following:
val counter = AtomicInteger()
counter.incrementAndGet()
Because the implementation of incrementAndGet() is atomic, we can use it easily to implement a thread-safe counter:
var counter = AtomicInteger()
fun asyncIncrement(by: Int) = async {
for (i in 0 until by) {
counter.incrementAndGet()
}
}
We can call it from main like in our original implementation...