Effective Kotlin: Concurrency

Let’s see how we can apply Joshua Bloch’s Effective Java in the Kotlin world. Today’s topic is Concurrency.

Item 78: Synchronize access to shared mutable data

In Kotlin, there is no longer the synchronized nor volatile keyword. Instead, it provides the following:

  • The synchronized() inline function to run the block of code while holding the monitor of the given lock.
  • The @Synchronized annotation to mark the annotated function as synchronized.
  • The @Volatile annotation to mark the annotated property as volatile.
  • The Mutex class for coroutines.

Item 79: Avoid excessive synchronization

There is nothing special in Kotlin for this item.

Item 80: Prefer executors, tasks, and streams to threads

In Kotlin, we can use coroutines and flows.

Item 81: Prefer concurrency utilities to wait and notify

In Kotlin, the root class Any no longer provides wait() nor notify(). However, if you really need to call them, you can try something like this.

Item 82: Document thread safety

There is nothing special in Kotlin for this item.

Item 83: Use lazy initialization judiciously

In Kotlin, we can use the lazy() delegate to lazily initialize properties in a thread-safe way.

Item 84: Don’t depend on the thread scheduler

There is nothing special in Kotlin for this item.


See also