Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Concurrency in Kotlin

You're reading from   Learning Concurrency in Kotlin Build highly efficient and scalable applications

Arrow left icon
Product type Paperback
Published in Jul 2018
Publisher Packt
ISBN-13 9781788627160
Length 266 pages
Edition 1st Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
Miguel Angel Castiblanco Torres Miguel Angel Castiblanco Torres
Author Profile Icon Miguel Angel Castiblanco Torres
Miguel Angel Castiblanco Torres
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. Hello, Concurrent World! 2. Coroutines in Action FREE CHAPTER 3. Life Cycle and Error Handling 4. Suspending Functions and the Coroutine Context 5. Iterators, Sequences, and Producers 6. Channels - Share Memory by Communicating 7. Thread Confinement, Actors, and Mutexes 8. Testing and Debugging Concurrent Code 9. The Internals of Concurrency in Kotlin 10. Other Books You May Enjoy

Atomic data structures

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...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime