CodeGym /Courses /Kotlin SELF /Producer–Consumer with Channel

Producer–Consumer with Channel

Kotlin SELF
Level 54, Lesson 1
Available

1. Getting to know the Producer–Consumer pattern

When you’re just learning to program, you want to solve everything simply: “let’s put tasks into a MutableList, and let the workers take them from there.” The logic is clear: task on top, processing below, and none of those “channels of yours”.

But as soon as concurrency shows up, MutableList turns into a knot of problems. Someone added an element, someone removed it, someone started iterating, someone “just a little bit” changed a counter—and you get bugs that happen once every 30 runs (i.e., perfect for ruining your day).

Producer–Consumer is useful because you separate roles and agree on who passes data, and how. In this picture, Channel acts like a “shared queue”, but without having to manually share the same mutable list. And this is very Kotlin-like: it’s better to make a clear contract than to rely on luck.

2. Terms and roles

The words Producer and Consumer sound like we’re selling a coffee subscription: “a producer of pleasure, a consumer of joy.” In practice it’s more mundane: a producer creates values, and a consumer processes them.

By the way, “producer/consumer” terminology also appears in other parts of the Kotlin world. For example, in generics there’s a handy mnemonic: “Producer reads (gives out), Consumer writes (takes in).” This is explained in the documentation about variance and the PECS idea (Producer-Extends, Consumer-Super). Today, our “producer/consumer” is not about types, but about a task stream; still, the intuition matches: the producer “produces” tasks, and consumers “consume” them and do the work.

For our scheme, you usually need four roles:

Role What it does Typical coroutine
Producer generates tasks and sends them to tasks
launch { ... tasks.send(...) ... }
Worker (Consumer) reads tasks from tasks, processes them, sends them to results
launch { for (t in tasks) results.send(...) }
Collector reads results and prints/saves them
launch/for (r in results) or simply a loop in runBlocking
Coordinator (sometimes separate) ensures channels get closed on time
launch { join(); close() }

Important: you can have multiple workers; the producer is usually one (but can be multiple), and the collector is most often one (but it can also be different).

3. Mini-project: TaskPipeline

So that the examples are not “in a vacuum”, we’ll build a small console application called TaskPipeline. It does a simple thing: a producer creates tasks (for example, numbers), several workers compute a “processing result” (for example, square them with a delay), and we print the outcomes.

Why the delay? Because without it, concurrency looks like magic: everything finishes instantly, and it feels like launch doesn’t do anything. So we’ll insert delay(...) to see how tasks are actually distributed.

Mini data models

Mini data models (it’s convenient to keep them in one file next to main):

data class Task(val id: Int, val value: Int)
data class TaskResult(val taskId: Int, val workerId: Int, val output: Int)

One task channel and multiple workers

The key Channel idea you need to feel in your hands: one message from a channel is received by exactly one consumer. This is not a broadcast “to everyone”; it’s a queue—“whoever got it, got it”.

So if we create 3 workers that read from the same Channel<Task>, tasks will be distributed automatically: whoever manages to receive gets the next piece of work.

Here is a minimal distribution example. Note: there is no results channel yet—we just print who processed what.

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.channels.Channel

fun main() = runBlocking {
    val tasks = Channel<Task>()

    repeat(2) { workerId ->
        launch {
            for (t in tasks) {
                delay(50) // simulate work
                println("worker=$workerId processed task=${t.id}") // e.g.: worker=1 processed task=3
            }
        }
    }

    repeat(5) { id ->
        tasks.send(Task(id = id, value = id * 10))
    }
    tasks.close()
}

Here, the producer is our runBlocking (the main coroutine), and the two launch blocks are consumers. We close tasks so that the for (t in tasks) loop finishes for each worker when tasks run out.

If you don’t close the channel, the workers will wait forever. It’s like inviting friends to a party but forgetting to tell them the party is already over: they’ll keep standing by the fridge and hoping.

4. Results channel and completion protocol

Adding results

Printing inside a worker is convenient for a demo, but in real life a worker usually doesn’t “decide on its own where to output.” It just does the work and passes the result along.

So we introduce a second channel:

  • tasks: Channel<Task> — task queue
  • results: Channel<TaskResult> — results queue

And now the worker sends its result to results.

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.channels.Channel

fun main() = runBlocking {
    val tasks = Channel<Task>()
    val results = Channel<TaskResult>()

    repeat(2) { workerId ->
        launch {
            for (t in tasks) {
                delay(50)
                val out = t.value * t.value
                results.send(TaskResult(t.id, workerId, out))
            }
        }
    }

    launch {
        repeat(5) { id -> tasks.send(Task(id, id + 1)) }
        tasks.close()
    }

    // For now, we manually read 5 results (a bit later we’ll do it nicely)
    repeat(5) {
        val r = results.receive()
        println("task=${r.taskId} by worker=${r.workerId} => ${r.output}")
        // e.g.: task=0 by worker=1 => 4
    }
}

And here the first serious problem arises: who should close results, and when?

Why closing channels is part of the contract

In a Producer–Consumer system, closing channels is not “the last line of the program”, but part of the contract.

The logic is:

  1. The producer stopped producing tasks → close tasks so workers can finish.
  2. The workers finished → they will no longer send results → now you can close results so the results collector can also finish.

The diagram (very simplified) looks like this:

flowchart LR
    P[Producer] -->|send Task| T[(tasks Channel)]
    T -->|receive Task| W1[Worker 1]
    T -->|receive Task| W2[Worker 2]
    W1 -->|send Result| R[(results Channel)]
    W2 -->|send Result| R
    R -->|receive Result| C[Collector]

    P -->|close tasks| T
    W1 -->|finish| X1(( ))
    W2 -->|finish| X2(( ))
    X1 -->|after join workers| R
    X2 -->|close results| R

The main subtlety: tasks.close() does not mean “it’s also safe to close results.” Workers may still be processing tasks they already received and trying to send a result. If you close results too early, a worker will crash on send.

That’s why the coordinator role appears: a coroutine (or just a piece of code) that waits for the senders to finish and only then closes the channel.

Canonical pipeline assembly

Let’s assemble a “canonical” (for our level) version where:

  • the producer creates tasks and closes tasks in finally;
  • workers read tasks until it’s closed and send results;
  • a separate coroutine waits for workers (join) and closes results;
  • the main thread reads results with a for loop (r in results) until it’s closed.
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.channels.Channel

fun main() = runBlocking {
    val tasks = Channel<Task>()
    val results = Channel<TaskResult>()

    val workers = List(2) { workerId ->
        launch {
            for (t in tasks) {
                delay(50)
                results.send(TaskResult(t.id, workerId, t.value * t.value))
            }
        }
    }

    val producer = launch {
        try {
            repeat(5) { id -> tasks.send(Task(id, id + 1)) }
        } finally {
            tasks.close()
        }
    }

    val closer = launch {
        producer.join()
        workers.joinAll()
        results.close()
    }

    for (r in results) {
        println("task=${r.taskId} by worker=${r.workerId} => ${r.output}")
    }

    closer.join()
}

Pay attention to the completion structure.

We don’t “guess” when it’s time to close results. We wait: first for the producer, then for all workers. Only after that do we close results, and the for loop (r in results) ends by itself. That’s the clean protocol.

The “closing owner” rule

There is a practical rule worth remembering like a spell against hangs:

The one who closes a channel is the one responsible for ensuring no one will send to it anymore.

It sounds pedantic, but in practice it saves you. If multiple workers send into results, then results should be closed not by “any of them whenever they feel like it”, but by the one who can guarantee that all of them have finished sending. Usually this is the coordinator (as in the example above), because it knows the list of worker Jobs and can wait for join().

If you try to close results inside a single worker, it will close the channel while other workers are still running. You’ll get a conflict: one already “shut the door”, while others are still trying to carry boxes in.

5. Result order and channel capacity

Why result order is not guaranteed

A question beginners often ask: “Will results arrive in the same order as tasks?”

And the honest answer is: they don’t have to. As soon as you have multiple workers, it becomes “whoever processed faster sent earlier.” So the collector receives results in readiness order, not in task.id order.

Sometimes that’s ideal (for example, when you show progress to the user). Sometimes you need to restore order. To restore order, people usually buffer results (for example, MutableMap<taskId, result>) or sort after collecting—but that’s a separate design topic, and for today it’s important that we at least don’t expect “magic ordering.”

A small example to see “out of order” behavior (different delays):

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.channels.Channel

fun main() = runBlocking {
    val tasks = Channel<Task>()
    val results = Channel<TaskResult>()

    launch {
        for (t in tasks) {
            delay((t.id + 1) * 30L) // different timings
            results.send(TaskResult(t.id, 0, t.value * 2))
        }
    }

    launch { repeat(3) { tasks.send(Task(it, 10)) }; tasks.close() }

    repeat(3) {
        println(results.receive()) // order may differ
    }
}

capacity and bottlenecks

Capacity (capacity) is “how many tasks you can put into the queue without waiting for them to be taken.” And it directly affects producer behavior.

If capacity = 0 (an unbuffered channel), send will wait until someone does a receive. It’s like passing a relay baton: until the second person takes it, the first person holds it and cannot “put it into a box.”

If capacity > 0, the producer can send several tasks ahead. It’s like a warehouse conveyor belt: you can place a few boxes, and only when the belt is full will you have to wait.

Mini experiment: one producer sends quickly, the consumer eats slowly.

import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.channels.Channel

fun main() = runBlocking {
    val tasks = Channel<Int>(capacity = 1)

    val consumer = launch {
        for (x in tasks) {
            delay(100)
            println("consumed $x") // consumed 0, then consumed 1, ...
        }
    }

    val producer = launch {
        repeat(3) { i ->
            println("sending $i")  // sending 0, sending 1, sending 2
            tasks.send(i)          // at i=2 it may wait until consumer frees space
        }
        tasks.close()
    }

    producer.join()
    consumer.join()
}

The important part is not to memorize “magic numbers”, but to understand the mechanics: capacity controls where exactly the system will wait—on the producer or on the consumer.

6. A small refactor for readability

When the pipeline gets longer, you really want to split everything into functions. That’s correct, but with coroutines it’s easy to make the code less clear if you “over-engineer” the architecture.

A good compromise: move coroutine creation into small helper functions that return Job. Then it’s convenient for the coordinator to wait for them.

Example: “create a worker”:

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.channels.ReceiveChannel
import kotlinx.coroutines.channels.SendChannel

fun CoroutineScope.launchWorker(
    workerId: Int,
    tasks: ReceiveChannel<Task>,
    results: SendChannel<TaskResult>
): Job = launch {
    for (t in tasks) {
        delay(50)
        results.send(TaskResult(t.id, workerId, t.value * t.value))
    }
}

And the producer:

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.channels.SendChannel

fun CoroutineScope.launchProducer(tasks: SendChannel<Task>, count: Int): Job = launch {
    try {
        repeat(count) { id -> tasks.send(Task(id, id + 1)) }
    } finally {
        // producer is the owner of the task channel, so it closes it
        tasks.close()
    }
}

This style is convenient because main turns into “wiring the scheme together” rather than a mess of nested launch calls.

7. Common mistakes in Producer–Consumer with Channel

Mistake #1: you forgot to close tasks, and workers “hang” in for (t in tasks).
This is the most common “why doesn’t the program terminate” scenario. A for loop over a channel ends only when the channel is closed and elements are exhausted. If the producer completes without close(), consumers will honestly wait for new tasks—like employees who were never told the office moved. The habit that saves you: close the channel in finally in the component that produces.

Mistake #2: you closed results too early.
The beginner logic is understandable: “there are no more tasks, so there will be no more results.” But workers may still be processing tasks they already received. If you close results at that moment, the next results.send(...) in a worker will end with an exception. The correct closing of results happens only after join() of all coroutines that send into it.

Mistake #3: multiple places in the code try to close the same channel.
When close() is scattered across the code, you lose the “protocol owner” and start catching weird effects: one closed it, another is still working, a third thinks the channel is alive. The fix is an agreement: each channel must have one logical place where it is closed (the producer or the coordinator), and it must be obvious when reading.

Mistake #4: the worker does heavy work, but sends the result nowhere and “prints it itself”.
For a demo that’s fine, but architecturally it quickly becomes inconvenient. As soon as you want to collect statistics instead of printing, compute progress, or change the output format, you’ll realize the output logic is spread across workers. It’s better to keep the worker a “clean result factory”: got a task → processed → sent the result to results.

Mistake #5: expecting “strict order” of results like in a normal loop.
With multiple workers, result order is readiness order, not task order. If some code implicitly assumes “task 0 first, then task 1”, it will start behaving oddly as soon as you add a second worker or change processing time. It’s better to design output as “arrived → processed”, or explicitly restore order with separate logic.

Mistake #6: ignoring cancellation and missing finally in the producer.
If the coroutine was cancelled or the producer throws an exception, the task channel may remain open and consumers may hang. try/finally { tasks.close() } makes behavior robust: even if everything goes off the rails, the system will correctly signal “no more tasks”, and consumers will finish.

1
Task
Kotlin SELF, level 54, lesson 1
Locked
Notification feed
Notification feed
1
Task
Kotlin SELF, level 54, lesson 1
Locked
Sum of orders
Sum of orders
1
Task
Kotlin SELF, level 54, lesson 1
Locked
Three Workers
Three Workers
1
Task
Kotlin SELF, level 54, lesson 1
Locked
Result pipeline
Result pipeline
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION