How to Write Thread-Safe Code With Kotlin

Alexandre Lombard
Level Up Coding
Published in
6 min readJun 9, 2020

--

Kotlin makes it easy to write thread-safe code (especially if we compare it to Java), yet the developer still have to follow some basic rules if he/she wants his/her code to be truly thread-safe. This story will present the main rules to follow, and the tools provided by Kotlin to follow them, but first let’s discuss what is thread-safe code.

Thread-safe code

When the code is meant to be run using several threads, there is a wide range of issues which can occur, mostly regrouped under the following categories:

  • Concurrent modification (or race condition): two threads simultaneously try to modify an object, if the object is a collection it will usually lead to a crash of the app; this issue is usually solved by using synchronized sections.
  • Deadlock (or livelock): when trying to use synchronized sections, we may create a situation where two threads are waiting on each other; this leads to a freeze of the app.

The golden rule to prevent these issues is to only use immutable objects. An immutable object is an object whose state cannot be changed after its creation. Thus, there is no risk of concurrent modification, and as there is no need of synchronization, we also prevent the risk of deadlocks. That’s also why in this article we will focus on techniques enabling thread-safety without the need of synchronization.

But as it seems easy to say, it’s usually harder to implement, especially when coming from a Java background where objects are traditionally stateful (POJO, beans, etc.). Fortunately, Kotlin provides a lot of syntactic sugar which will help us to make immutable objects, and more generally thread-safe code, without losing too much performance.

Use val as much as possible

When declaring a variable or a class member in Kotlin, we have the choice between two keywords: val and var.

var basically means that the value of the reference or the variable can be changed, while val means it will be constant (initialized only once).

If we want to create an immutable object, then all of its members should be declared with the val keyword. The var keyword should only be used for local variables (i.e…

--

--

PhD and associate professor at UTBM (France), co-founder of Isara Tech., I’m interested in all fields of IT, with a preference for 3D and simulation.