Thread safety

There are many books written about thread safety and there are good reasons for that. Concurrency bugs that are caused by lack of thread safety are the ones hardest to track. They're hard to reproduce, because you'll usually need a lot of threads competing on the same resource for an actual race to happen. Because this book is about Kotlin and not thread safety in general, we'll only scratch the surface of this topic. If you're interested in the topic of thread safety in the JVM language, you should check out the book Java Concurrency in Practice by Brian Goetz.

We'll start with the following example, which creates 100,000 threads to increment a counter:

var counter = 0
val latch = CountDownLatch(100_000)
for (i in 1..100_000) {
thread {
counter++
latch.countDown()
}
}

latch.await()
println("Counter $counter")

If you have a bit of experience with concurrent programming, you'll understand right away why this code prints a number that is less than 100,000. The reason is the ++ operation is not atomic. So the more threads that try to increment our counter, the more chances for data races. 

But, unlike Java, there's no synchronized keyword in Kotlin. The reason is that Kotlin designers believe that a language shouldn't be tailored to a particular concurrency model. Instead, there's a synchronized() function:

var counter = 0
val latch = CountDownLatch(100_000)
for (i in 1..100_000) {
thread{
synchronized(latch) {
counter++
latch.countDown()
}
}
}

latch.await()
println("Counter $counter")

Now our code prints 100000, as expected.

If you really miss the synchronized methods from Java, there's the @Synchronized annotation in Kotlin. There's also no volatile keyword, but the @Volatile annotation instead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.135.249