CodeGym /Courses /Kotlin SELF /Race conditions and compound operations on shared state

Race conditions and compound operations on shared state

Kotlin SELF
Level 55, Lesson 0
Available

1. Introduction

When you start writing coroutines, it’s easy to fall into an illusion: “Well, these aren’t threads, so thread hazards don’t apply.” Unfortunately (or fortunately—otherwise it would be boring), coroutines can absolutely run concurrently, and on Dispatchers.Default they also run in parallel on a thread pool. That means two coroutines can literally execute your code at the same time on different CPU cores.

The official coroutine materials emphasize that coroutines are started via builders (launch, async), and their behavior is defined by the context, including CoroutineDispatcher, which decides “where the coroutine runs.”

As soon as we have concurrent execution, we get the “good old” class of multithreading problems: races, races, and races again. Coroutines are modern and convenient, but they don’t cancel the scheduler’s laws.

Shared mutable state

Before blaming race conditions, we need to agree on terms. Shared mutable state means “shared mutable state.” In other words, there’s some data that is simultaneously available for writing from multiple coroutines. The key is “for writing”: if everyone only reads, it’s usually safer (though there can be nuances there too).

An example of shared mutable state is a variable var counter = 0 that many coroutines increment at once. Or var balance = 100 that multiple coroutines try to withdraw money from. Or a MutableList that several coroutines append to while other coroutines iterate over it.

The problem with shared mutable state is that it breaks not “according to the logic of the code,” but according to how, at a specific moment in time, the execution steps got interleaved. And that feels less like programming and more like trying to negotiate with a cat that decides on its own whether it will be affectionate today.

2. Compound operations: where exactly the race is hiding

counter++ is not a single operation

Here comes the moment that ruins beginners’ lives (and sometimes even non-beginners’): counter++ looks like one operation, but semantically it’s at least three steps:

1) read counter from memory into a register/variable,
2) add 1,
3) write the new value back into counter.

If a single coroutine executes these steps, everything is great. But if two coroutines do it at the same time, they can “step on each other’s writes.”

Imagine both coroutines read counter = 10. Both compute 10 + 1. And both write 11. Result: instead of two increments, you get one. No mysticism—just logic getting overwritten.

Here’s a small example that often shows the problem even on a regular laptop:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    var counter = 0

    val jobs = List(1_000) {
        launch(Dispatchers.Default) {
            counter++ // race: read → add → write
        }
    }

    jobs.forEach { it.join() }
    println(counter) // often < 1000
}

If you’re lucky, you’ll see something like 972, 998, 1000… and that “sometimes 1000” is a separate source of moral pain. Because a bug that “sometimes doesn’t show up” usually shows up during a demo in front of your manager.

Why races look like magic

A very unpleasant feature of race conditions is unpredictability. The thread/coroutine scheduler (simplifying) decides who gets CPU time and when. It decides quickly, often, and doesn’t ask for your opinion. On one machine, in one run, you get one interleaving. On the next run, a different one. And if you add a println, things may “fix themselves” (because output is slow, and the interleaving changes).

To feel this firsthand, it’s useful to run the same experiment several times and watch the result “wander”:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    repeat(5) { attempt ->
        var counter = 0

        val jobs = List(1_000) {
            launch(Dispatchers.Default) { counter++ }
        }

        jobs.forEach { it.join() }
        println("attempt=$attempt counter=$counter") // attempts differ
    }
}

What matters here isn’t that the result is “sometimes not 1000,” but that it can be different every time. That’s the main emotional marker of races: your logic is one, but reality is new each run.

Check-then-act: “checked → acted” as a trap

If counter++ is a classic race, then check-then-act is its more devious relative. This is when you first check a condition, then perform an action, and it seems safe because “well, I checked.” But between the check and the action, another coroutine can slip in and change the state.

Let’s imagine a mini scenario: a small ticket “booth.” There’s a variable tickets = 1. Two coroutines are trying to buy a ticket: “if tickets exist—decrease by 1.”

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    var tickets = 1

    val j1 = launch(Dispatchers.Default) {
        if (tickets > 0) {
            delay(10)         // increase the chance of interleaving
            tickets -= 1
        }
    }

    val j2 = launch(Dispatchers.Default) {
        if (tickets > 0) {
            delay(10)
            tickets -= 1
        }
    }

    j1.join()
    j2.join()
    println("tickets=$tickets") // can become -1
}

The trick is that both coroutines can make it through the check tickets > 0 while tickets is still 1. Then both perform the decrement—and we get -1. In real life, that’s called “sold two tickets for one seat,” and in programming it’s “we just created a bug that will cost money and reputation.”

Note: the problem here isn’t delay. delay just makes the race easier to observe. The race exists without it too—it can just hide better.

3. Invariants and critical sections

What exactly are we protecting

When the conversation turns to concurrency, it’s tempting to say: “Okay, I’ll protect everything.” But that leads to code that either slows down or turns into incomprehensible mush. So we need an important word: invariant.

An invariant is an integrity rule that must remain true always, despite concurrency. In the case of our ticket booth, possible invariants include:

State Invariant (rule) Why it matters
tickets
tickets >= 0
you can’t sell more tickets than you have
sold and tickets
sold + tickets == totalTickets
the number of tickets must not “appear out of thin air”
balance
balance >= 0
you can’t go negative if the rules forbid it

The most useful thing about invariants is that they answer the question: “What exactly do we need to make indivisible?” In other words, what logic must we not allow other coroutines to “tear apart” in the middle.

For example, in check-then-act an invariant often breaks because the check and the change must be one “atomic” block in meaning: “checked and immediately acted, without yielding control between them.”

How to find the “minimal chunk” that must not be interrupted

The term critical section sounds like we’re about to build a bunker. In reality, the meaning is simpler: a critical section is a piece of code that must run as if it’s the “only one” at that moment. That is, while one coroutine executes that piece, others must not simultaneously execute a conflicting piece over the same state.

But in this lecture, what matters is not “how to protect a critical section” (tools will come later), but how to identify it correctly. A useful exercise here is “pencil over the code”:

You take the area where shared state is read and written, and ask yourself: “If I get interrupted right after this line, can the invariant already be violated?” If yes, then the boundary of the critical section is chosen incorrectly, and you need to expand the block so it includes dependent steps.

For tickets it looks like this:

if (tickets > 0) {   // read tickets and made a decision
    tickets -= 1     // wrote tickets
}

If we’re interrupted between the lines, another coroutine can make the same decision based on the old value. So both lines must be treated as a single “indivisible” chunk—one logical purchase operation.

A good rule for a beginner: if the logic looks like “read → decide → write”, it’s almost certainly a candidate for a critical section. Even if the code is only two lines.

4. TicketOffice training playground

So the examples don’t hang in mid-air, let’s set up a small training app that we’ll “grow” in the next lectures. For now it will be intentionally unsafe—and that’s fine: we’re building a “broken bike” so we can later understand which bolts need tightening.

Let’s start with the simplest model: a ticket office stores tickets and sold. Selling is check-then-act. For now, with no protection at all.

import kotlinx.coroutines.delay

suspend fun buyTicketUnsafe(): Boolean {
    if (tickets > 0) {
        delay(1)          // increase the chance of a race, does NOT "fix" the problem
        tickets -= 1
        sold += 1
        return true
    }
    return false
}

But there’s a nuance: Kotlin doesn’t like “naked” global vars, and that’s correct. So we’ll make the simplest possible “box” for state via IntArray (so we can mutate elements by passing them by reference), without going deep into OOP yet. It looks a bit hacky, but it’s transparent for understanding.

import kotlinx.coroutines.delay

suspend fun buyTicketUnsafe(state: IntArray): Boolean {
    val tickets = state[0]
    if (tickets > 0) {
        delay(1)
        state[0] = tickets - 1  // tickets
        state[1] += 1           // sold
        return true
    }
    return false
}

Now let’s write main that runs many “buyers” in parallel. We expect sold not to exceed the initial tickets. But reality may surprise us.

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val state = intArrayOf(10, 0) // [tickets=10, sold=0]

    val buyers = List(1_000) {
        launch(Dispatchers.Default) {
            buyTicketUnsafe(state)
        }
    }

    buyers.forEach { it.join() }
    println("tickets=${state[0]}, sold=${state[1]}") // may be weird
}

Why can the result be “weird”? Because we protected nothing. We read tickets into a local variable, then wait delay(1), then write it back. During that time, another coroutine could do the same thing, and some sales will get “overwritten.” Or, if you change the logic to a more direct one (state[0] -= 1 after the check), you can get other kinds of breakage.

The main takeaway: as soon as you see shared mutable state and compound logic, you must suspect a race.

5. How an update gets “lost”

Sometimes it’s useful not just to take it on faith, but to see a “cartoon” of step interleaving. Here’s schematically how one increment is lost with counter++:

sequenceDiagram
    participant A as Coroutine A
    participant B as Coroutine B
    participant M as counter (memory)

    A->>M: read counter (=10)
    B->>M: read counter (=10)
    A->>A: compute 10+1 (=11)
    B->>B: compute 10+1 (=11)
    A->>M: write 11
    B->>M: write 11
    Note over M: Result = 11, even though it "should" be 12

For check-then-act the diagram is similar, except instead of “added 1” we have “checked the condition and decremented.” And in both cases the key problem is the same: another coroutine can slip in between logically related steps.

6. Typical mistakes

Mistake #1: thinking “coroutines aren’t threads, so there are no races.”
Coroutines are indeed lighter and cheaper than threads, but they can easily run on a thread pool, especially on Dispatchers.Default, and can run in parallel. If multiple coroutines write to one variable without coordination, you get a classic race.

Mistake #2: assuming races only happen with counter++.
++ is just a very visual example because it looks like “one line.” But any compound logic of the form “read → compute → write” or “check → act” is subject to the same problems. Especially check-then-act: it looks “reasonable,” but breaks most often.

Mistake #3: concluding “it printed 1000 once, so it’s fine.”
Race conditions are devious because they might not show up in a single run. They depend on timing, CPU load, background processes, and even whether you have a browser tab with music open. Reliability built on luck usually ends abruptly.

Mistake #4: trying to “fix” a race by adding delay() or “one more println”.
delay and println change the execution schedule, so the bug may “hide” or “pop up” more often. But they don’t remove the cause. It’s like treating a crack in a wall with a sticker saying “don’t crack”: the wall doesn’t care.

Mistake #5: not formulating an invariant and therefore protecting “everything at once.”
If you can’t state what integrity rule must always hold (tickets >= 0, sold + tickets == total, etc.), you won’t be able to correctly identify the critical section. This usually ends with either protecting too small a piece (the race remains) or too large a piece (the program becomes slow and awkward).

Mistake #6: confusing “shared access” with “shared writes.”
Sometimes a student sees that a variable is accessible from different places and starts panicking. But the real risk zone is when data has concurrent writes. Reading by itself is more often safe (though there are subtleties), but writing without coordination is almost guaranteed to be a candidate for problems.

1
Task
Kotlin SELF, level 55, lesson 0
Locked
Broken Counter
Broken Counter
1
Task
Kotlin SELF, level 55, lesson 0
Locked
Tickets Going Negative
Tickets Going Negative
1
Task
Kotlin SELF, level 55, lesson 0
Locked
Box Office Invariants
Box Office Invariants
1
Task
Kotlin SELF, level 55, lesson 0
Locked
Manual scheduler
Manual scheduler
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION