Locks and synchronization

suggest change

When several threads or coroutines share mutable state, you need a way to make some operations happen one at a time and to make sure each side sees the other's writes. Race conditions shows what goes wrong without that and compares the main fixes (atomics, locks, confinement, message passing). This article goes deeper into the locks themselves: which ones Kotlin gives you, how they behave, and the mistakes that cause deadlocks and hangs.

On the JVM, Kotlin code can use:

The rule of thumb: thread code uses JVM locks, coroutine code uses Mutex and Semaphore. The Dispatchers and threads article explains which threads your coroutines actually run on, which matters for the second half of this article.

The coroutine examples use this dependency:

// build.gradle.kts
dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
}

synchronized

synchronized is an inline function from the Kotlin standard library. It takes any object as the lock, runs the block while holding that object's monitor, and releases it when the block exits, whether normally, by return, or by an exception. It returns the value of the block:

import kotlin.concurrent.thread

class Inventory {
    private val lock = Any()
    private val stock = mutableMapOf<String, Int>()

    fun add(item: String, qty: Int) = synchronized(lock) {
        stock[item] = (stock[item] ?: 0) + qty
    }

    // synchronized returns the value of its block
    fun take(item: String, qty: Int): Boolean = synchronized(lock) {
        val have = stock[item] ?: 0
        if (have < qty) return false   // early return releases the lock
        stock[item] = have - qty
        true
    }

    // calls add() while already holding the lock: monitors are reentrant
    fun restock(items: Map<String, Int>) = synchronized(lock) {
        items.forEach { (k, v) -> add(k, v) }
    }

    fun count(item: String): Int = synchronized(lock) { stock[item] ?: 0 }
}

fun main() {
    val inv = Inventory()
    inv.restock(mapOf("apple" to 1000))
    val taken = java.util.concurrent.atomic.AtomicInteger()
    val threads = List(4) {
        thread {
            repeat(300) { if (inv.take("apple", 1)) taken.incrementAndGet() }
        }
    }
    threads.forEach { it.join() }
    println("taken = ${taken.get()}, left = ${inv.count("apple")}")
}
taken = 1000, left = 0

Four threads try to take 1,200 apples in total, but exactly 1,000 succeed: the check and the update in take run as one step.

Points worth knowing:

wait and notify

Kotlin's Any has no wait() / notify() methods. If you really want to use the monitor's wait set, the lock must be a java.lang.Object:

import kotlin.concurrent.thread

class Mailbox {
    private val lock = Object()       // java.lang.Object, not Any
    private var message: String? = null

    fun send(msg: String) = synchronized(lock) {
        message = msg
        lock.notifyAll()
    }

    fun receive(): String = synchronized(lock) {
        while (message == null) lock.wait()
        message!!.also { message = null }
    }
}

fun main() {
    val box = Mailbox()
    val t = thread { println("received: ${box.receive()}") }
    Thread.sleep(100)
    box.send("hello")
    t.join()
}
received: hello

The compiler warns: "This class is not recommended for use in Kotlin. Use 'kotlin.Any' instead." That's a hint that you should use something else. A ReentrantLock with a Condition (below), a BlockingQueue, or a coroutine Channel does the same job more clearly. Note the while loop around wait(): wakeups can be spurious, so always re-check the condition.

ReentrantLock

ReentrantLock from java.util.concurrent.locks behaves like a monitor but has more features: try-lock, timeouts, interruptible waiting, multiple conditions, and introspection. Always use Kotlin's withLock extension (or try/finally) so the lock is released even when the block throws:

import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.thread
import kotlin.concurrent.withLock

val lock = ReentrantLock()

fun main() {
    lock.withLock {
        lock.withLock {
            println("held by me: ${lock.isHeldByCurrentThread}, hold count: ${lock.holdCount}")
        }
        println("hold count after inner block: ${lock.holdCount}")
    }

    // another thread holds the lock for 300 ms
    val holder = thread {
        lock.withLock { Thread.sleep(300) }
    }
    Thread.sleep(50)

    println("tryLock(): ${lock.tryLock()}")  // returns immediately

    if (lock.tryLock(1, TimeUnit.SECONDS)) {  // waits up to 1 second
        try {
            println("got the lock after waiting, queued threads: ${lock.queueLength}")
        } finally {
            lock.unlock()
        }
    } else {
        println("timed out")
    }
    holder.join()
}
held by me: true, hold count: 2
hold count after inner block: 1
tryLock(): false
got the lock after waiting, queued threads: 0

The main API:

Method What it does
lock() / unlock() acquire / release; each lock() needs exactly one unlock()
withLock { } Kotlin extension: lock, run the block, unlock in finally
tryLock() take the lock only if it's free right now
tryLock(timeout, unit) wait up to the timeout, return false if still unavailable
lockInterruptibly() wait, but give up with InterruptedException if the thread is interrupted
newCondition() create a Condition to wait on (replaces wait/notify)
isHeldByCurrentThread, holdCount, isLocked, queueLength introspection for assertions and debugging

ReentrantLock(true) creates a fair lock that hands the lock to the longest-waiting thread. The default unfair lock gives better throughput; use a fair one only if you see threads starving.

Calling unlock() from a thread that doesn't hold the lock throws IllegalMonitorStateException. That matters for coroutines, as shown later.

Conditions

A Condition lets threads wait inside the lock until some state changes. await() releases the lock while waiting and takes it back before returning. Unlike a monitor, one lock can have several conditions, so producers and consumers wake only each other. Here is a bounded buffer:

import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.thread
import kotlin.concurrent.withLock

class BoundedBuffer<T>(private val capacity: Int) {
    private val lock = ReentrantLock()
    private val notFull = lock.newCondition()
    private val notEmpty = lock.newCondition()
    private val items = ArrayDeque<T>()

    fun put(item: T) = lock.withLock {
        while (items.size == capacity) notFull.await()  // releases the lock while waiting
        items.addLast(item)
        notEmpty.signal()
    }

    fun take(): T = lock.withLock {
        while (items.isEmpty()) notEmpty.await()
        val item = items.removeFirst()
        notFull.signal()
        item
    }
}

fun main() {
    val buffer = BoundedBuffer<Int>(capacity = 2)
    val consumer = thread {
        var sum = 0
        repeat(10) { sum += buffer.take() }
        println("consumer sum = $sum")
    }
    for (i in 1..10) buffer.put(i)
    consumer.join()
}
consumer sum = 55

This is a good way to learn how conditions work. In real code use ArrayBlockingQueue (threads) or Channel(capacity) (coroutines), which already implement exactly this.

Read-write locks

If a structure is read much more often than it's written, a ReentrantReadWriteLock lets any number of readers in at once while writers get exclusive access. Kotlin's read { } and write { } extensions handle locking and unlocking:

import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.thread
import kotlin.concurrent.write

class RouteTable {
    private val rw = ReentrantReadWriteLock()
    private val routes = mutableMapOf("/" to "home")

    fun lookup(path: String): String? = rw.read {
        Thread.sleep(100) // pretend lookups are slow
        routes[path]
    }

    fun register(path: String, handler: String) = rw.write {
        routes[path] = handler
    }

    // read first, upgrade to write only if needed
    fun registerIfMissing(path: String, handler: String): Boolean = rw.read {
        if (routes.containsKey(path)) return false
        rw.write {             // releases our read lock, then takes the write lock
            if (routes.containsKey(path)) return false // re-check: state may have changed
            routes[path] = handler
            true
        }
    }
}

fun main() {
    val table = RouteTable()
    val start = System.nanoTime()
    val readers = List(5) { thread { table.lookup("/") } }
    readers.forEach { it.join() }
    val ms = (System.nanoTime() - start) / 1_000_000
    println("5 parallel reads took less than 300 ms: ${ms < 300}")

    println(table.registerIfMissing("/about", "about"))
    println(table.registerIfMissing("/about", "other"))
    println(table.lookup("/about"))
}
5 parallel reads took less than 300 ms: true
true
false
about

Five 100 ms reads finish together instead of one after another, because they hold the read lock at the same time.

registerIfMissing shows a subtle point. With plain ReentrantReadWriteLock, a thread holding the read lock that calls writeLock().lock() deadlocks forever: the write lock waits for all readers to leave, including itself. Kotlin's write { } extension avoids that by releasing the current thread's read locks first and re-acquiring them afterwards. The price is that another writer can slip in during the gap, so re-check the condition inside write.

Read-write locks have more overhead than a plain lock. They pay off only when reads are frequent and the read section does real work. For a map, ConcurrentHashMap is usually a better choice than a map guarded by a read-write lock.

StampedLock and optimistic reads

StampedLock adds an optimistic read mode: read without locking, then check whether a write happened in the meantime. If it did, retry under a real read lock:

import java.util.concurrent.locks.StampedLock
import kotlin.concurrent.thread

class Point {
    private val sl = StampedLock()
    private var x = 0.0
    private var y = 0.0

    fun move(dx: Double, dy: Double) {
        val stamp = sl.writeLock()
        try {
            x += dx
            y += dy
        } finally {
            sl.unlockWrite(stamp)
        }
    }

    fun distanceFromOrigin(): Double {
        var stamp = sl.tryOptimisticRead()  // no locking at all
        var cx = x
        var cy = y
        if (!sl.validate(stamp)) {          // a write happened in between: fall back
            stamp = sl.readLock()
            try {
                cx = x
                cy = y
            } finally {
                sl.unlockRead(stamp)
            }
        }
        return Math.hypot(cx, cy)
    }
}

fun main() {
    val p = Point()
    val writer = thread { repeat(100_000) { p.move(3.0, 4.0) } }
    repeat(100_000) { p.distanceFromOrigin() } // reads run while the writer is busy
    writer.join()
    println("final distance = ${p.distanceFromOrigin()}")
}
final distance = 500000.0

StampedLock is not reentrant and has no withLock helper, so it's easy to misuse. Only read plain fields in the optimistic section and don't act on the values until validate returns true. Reach for it only when profiling shows a read-write lock is a bottleneck.

Deadlocks

A deadlock happens when two threads each hold a lock the other needs. Neither can continue, and with synchronized or lock() they wait forever. Here's one, plus how to detect it with ThreadMXBean:

import java.lang.management.ManagementFactory
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.thread
import kotlin.concurrent.withLock

val a = ReentrantLock()
val b = ReentrantLock()

fun main() {
    val t1 = thread(name = "worker-1", isDaemon = true) {
        a.withLock { Thread.sleep(100); b.withLock { println("t1 done") } }
    }
    val t2 = thread(name = "worker-2", isDaemon = true) {
        b.withLock { Thread.sleep(100); a.withLock { println("t2 done") } }
    }
    Thread.sleep(500)

    val mx = ManagementFactory.getThreadMXBean()
    val ids = mx.findDeadlockedThreads() ?: longArrayOf()
    for (info in mx.getThreadInfo(ids)) {
        println("${info.threadName} is waiting for ${info.lockName.substringBefore('@')} held by ${info.lockOwnerName}")
    }
}

Example output (the order of the lines can vary):

worker-1 is waiting for java.util.concurrent.locks.ReentrantLock$NonfairSync held by worker-2
worker-2 is waiting for java.util.concurrent.locks.ReentrantLock$NonfairSync held by worker-1

The threads are daemons only so this demo can exit; normally a deadlock hangs the program. In a running application, jstack <pid> (or jcmd <pid> Thread.print) prints a thread dump that ends with a "Found one Java-level deadlock" section listing the same information.

The standard fix is a global lock order: whenever code needs several locks, it always takes them in the same order. For example, lock bank accounts by id:

import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.thread
import kotlin.concurrent.withLock

class Account(val id: Int, var balance: Long) {
    val lock = ReentrantLock()
}

fun transfer(from: Account, to: Account, amount: Long) {
    // always lock the account with the smaller id first
    val (first, second) = if (from.id < to.id) from to to else to to from
    first.lock.withLock {
        second.lock.withLock {
            from.balance -= amount
            to.balance += amount
        }
    }
}

fun main() {
    val x = Account(1, 1000)
    val y = Account(2, 1000)
    val t1 = thread { repeat(100_000) { transfer(x, y, 1) } }
    val t2 = thread { repeat(100_000) { transfer(y, x, 1) } }
    t1.join(); t2.join()
    println("x = ${x.balance}, y = ${y.balance}")
}
x = 1000, y = 1000

Other ways to avoid deadlocks:

Mutex for coroutines

A JVM lock blocks the thread while waiting, and the compiler refuses to compile a suspension point inside synchronized. Coroutine code should use Mutex from kotlinx.coroutines.sync. Waiting for a Mutex suspends the coroutine (the thread goes on running other coroutines), and the body of withLock may call suspending functions.

A typical use is making sure only one coroutine does an expensive refresh while the others wait for its result:

import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

class TokenCache(private val fetch: suspend () -> String) {
    private val mutex = Mutex()
    @Volatile private var token: String? = null

    // only one coroutine refreshes; the others wait (suspended) and reuse its result
    suspend fun get(): String = token ?: mutex.withLock {
        token ?: fetch().also { token = it }
    }
}

fun main() = runBlocking {
    var fetches = 0
    val cache = TokenCache {
        fetches++
        delay(100)          // network call while holding the mutex: allowed
        "token-42"
    }
    val tokens = withContext(Dispatchers.Default) {
        List(50) { async { cache.get() } }.awaitAll()
    }
    println("${tokens.toSet()} fetched $fetches time(s)")

    val m = Mutex()
    println("tryLock: ${m.tryLock()}, isLocked: ${m.isLocked}")
    println("tryLock again: ${m.tryLock()}")  // not reentrant, even for the same caller
    m.unlock()

    // owner tokens catch mistakes
    val owner = Any()
    m.lock(owner)
    println("holdsLock(owner): ${m.holdsLock(owner)}")
    try {
        m.lock(owner)   // same owner again: fails fast instead of deadlocking
    } catch (e: IllegalStateException) {
        println("error: ${e.message?.substringBefore(":")}")
    }
    m.unlock(owner)
}
[token-42] fetched 1 time(s)
tryLock: true, isLocked: true
tryLock again: false
holdsLock(owner): true
error: This mutex is already locked by the specified owner

The token field is read outside the mutex on the fast path, so it's @Volatile to guarantee that other threads see the written value. The second check inside withLock stops coroutines that were waiting from fetching again.

How Mutex differs from ReentrantLock:

Keep withLock blocks short. Holding a mutex across a slow network call (as TokenCache does) is fine when that's the point, but holding one across unrelated work serializes every caller.

Don't hold JVM locks across suspension points

The compiler catches delay() inside synchronized, but not inside ReentrantLock.lock() / unlock(), because those are ordinary method calls. The code compiles and then fails at runtime: after delay the coroutine may resume on a different thread of the dispatcher, and ReentrantLock only lets the owning thread unlock it:

import kotlinx.coroutines.*
import java.util.concurrent.locks.ReentrantLock

fun main() = runBlocking {
    withContext(Dispatchers.Default) {
        repeat(4) { i ->
            launch {
                val lock = ReentrantLock()
                lock.lock()
                val lockedOn = Thread.currentThread().name
                try {
                    delay(100)   // compiles, but may resume on another thread
                } finally {
                    val unlockOn = Thread.currentThread().name
                    try {
                        lock.unlock()
                        println("$i: locked and unlocked on $lockedOn")
                    } catch (e: IllegalMonitorStateException) {
                        println("$i: locked on $lockedOn, unlock on $unlockOn -> ${e::class.simpleName}")
                    }
                }
            }
        }
    }
}

Example output (varies from run to run):

3: locked and unlocked on DefaultDispatcher-worker-5
2: locked on DefaultDispatcher-worker-4, unlock on DefaultDispatcher-worker-3 -> IllegalMonitorStateException
1: locked on DefaultDispatcher-worker-3, unlock on DefaultDispatcher-worker-2 -> IllegalMonitorStateException
0: locked on DefaultDispatcher-worker-2, unlock on DefaultDispatcher-worker-4 -> IllegalMonitorStateException

Sometimes it works, which makes the bug worse. And the lock stays held by the original thread forever, so the next lock() call blocks. withLock { } from kotlin.concurrent has the same problem if its block suspends.

It's fine to use a JVM lock inside a coroutine for a short, non-suspending critical section (updating a map, incrementing two fields). As soon as the critical section needs to suspend, use Mutex.

Semaphore

A semaphore holds a number of permits. Acquiring takes one (waiting if none are left) and releasing gives it back. With one permit it's a lock; with more, it limits how many callers can be inside at once. The coroutine version, kotlinx.coroutines.sync.Semaphore, is a common way to cap concurrent requests:

import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import java.util.concurrent.atomic.AtomicInteger

val inFlight = AtomicInteger()
val maxInFlight = AtomicInteger()

suspend fun download(id: Int): String {
    val now = inFlight.incrementAndGet()
    maxInFlight.accumulateAndGet(now, ::maxOf)
    delay(50)
    inFlight.decrementAndGet()
    return "file-$id"
}

fun main() = runBlocking {
    val limit = Semaphore(permits = 3)
    val files = withContext(Dispatchers.Default) {
        (1..20).map { id ->
            async { limit.withPermit { download(id) } }
        }.awaitAll()
    }
    println("downloaded ${files.size} files, max in flight = ${maxInFlight.get()}")
    println("available permits after: ${limit.availablePermits}")
}
downloaded 20 files, max in flight = 3
available permits after: 3

All 20 coroutines start immediately, but only 3 are ever inside download at once. withPermit releases the permit even if the block throws or the coroutine is cancelled.

A semaphore limits how many, not which ones: the 3 coroutines inside still run in parallel and need their own protection if they share state. To limit parallelism of a dispatcher rather than of one code section, see limitedParallelism in Dispatchers and threads.

Latches, barriers and blocking semaphores

java.util.concurrent has a few more coordination tools for thread code:

import java.util.concurrent.CountDownLatch
import java.util.concurrent.CyclicBarrier
import java.util.concurrent.Semaphore
import kotlin.concurrent.thread

fun main() {
    // CountDownLatch: wait until N things have happened
    val ready = CountDownLatch(3)
    repeat(3) { i ->
        thread {
            Thread.sleep(50L * i)
            println("service $i started")
            ready.countDown()
        }
    }
    ready.await()
    println("all services ready")

    // CyclicBarrier: N threads wait for each other, then all continue
    val barrier = CyclicBarrier(3) { println("--- phase done ---") }
    val workers = List(3) { i ->
        thread {
            repeat(2) {
                Thread.sleep(10L * (i + 1))
                barrier.await()
            }
        }
    }
    workers.forEach { it.join() }

    // java.util.concurrent.Semaphore: blocking version for threads
    val pool = Semaphore(2)
    if (pool.tryAcquire()) {
        try {
            println("got a permit, ${pool.availablePermits()} left")
        } finally {
            pool.release()
        }
    }
}
service 0 started
service 1 started
service 2 started
all services ready
--- phase done ---
--- phase done ---
got a permit, 1 left

In coroutine code you rarely need these: job.join(), awaitAll(), CompletableDeferred and Channel cover the same ground without blocking threads.

Locks and virtual threads

JDK 21 added virtual threads, which are cheap enough to create one per task. In JDK 21 through 23, blocking inside synchronized pinned the virtual thread to its carrier (platform) thread, so long waits inside synchronized could starve the carrier pool, and ReentrantLock was the recommended replacement. Since JDK 24 (JEP 491), virtual threads can block inside synchronized without pinning, so both kinds of lock work well. If you deploy on JDK 21 with virtual threads, prefer ReentrantLock around anything that blocks.

Choosing a lock

Situation Use
short critical section in thread code synchronized(lock) with a private lock object
need a timeout, try-lock, interruptible wait, or several conditions ReentrantLock + withLock
many readers, few writers, real work in reads ReentrantReadWriteLock + read { } / write { }
read-mostly hot path, measured bottleneck StampedLock optimistic reads
critical section in coroutines, may suspend Mutex.withLock
limit concurrent operations in coroutines Semaphore.withPermit
limit concurrent operations in threads java.util.concurrent.Semaphore
wait for N events / N threads CountDownLatch / CyclicBarrier (threads), awaitAll() / join() (coroutines)
single counter or reference an atomic class instead of a lock (see Race conditions)

Gotchas

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents