Learn Kotlin Β· 16/18

Coroutines II: Concurrency Management

7 min read

Coroutines II: Concurrency Management 🚦

Welcome back! Having grasped the basics of coroutines, it's time to level up and learn how to manage them effectively. Think of our last session as learning to drive a car. Now, we're going to learn the rules of the road, how to handle traffic, and what to do when things go unexpectedly wrong. In this guide, we'll explore the essential concepts for managing concurrency in Kotlin coroutines.

1. Jobs and Cancellation: Stopping Background Work πŸ›‘

The Problem: Imagine you start a background task, like downloading a large file. What happens if the user navigates away from the screen before the download is complete? Without a way to stop it, the download would continue in the background, wasting precious resources like data and battery. This is where the concept of a Job and cancellation comes into play.

The Solution: The Job

Every time you launch a coroutine using launch, it returns a Job instance. This Job is essentially a handle to the coroutine, allowing you to manage its lifecycle. You can think of it as a remote control for your background task.

Key Concepts:

  • Job: Represents a coroutine's lifecycle and can be used to cancel it.
  • Cancellation: The process of stopping a coroutine's execution. Cancellation in coroutines is cooperative, meaning the coroutine code must be written to be cancellable.

Let's see it in action:

kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val job = launch {
        repeat(1000) { i ->
            println("I'm sleeping $i ...")
            delay(500L)
        }
    }
    delay(1300L) // let it work for a bit
    println("main: I'm tired of waiting!")
    job.cancel() // cancels the job
    job.join() // waits for job's completion
    println("main: Now I can quit.")
}

In this example, we launch a coroutine that prints a message every half a second. After 1.3 seconds, we've had enough and call job.cancel(). The job.join() call then waits for the coroutine to finish its cancellation process. If you run this, you'll see the coroutine stops printing after being canceled.

Fun Fact: A canceled coroutine throws a CancellationException. This is a special kind of exception that is generally ignored by exception handlers. It's the coroutine's way of saying, "I've been asked to stop, so I'm gracefully shutting down."

2. Structured Concurrency: CoroutineScope and Context πŸ‘¨β€πŸ‘©β€πŸ‘§β€πŸ‘¦

The Problem: What if you launch multiple coroutines? How do you keep track of them all? Manually managing the lifecycle of every single coroutine can quickly become a nightmare. You might forget to cancel one, leading to resource leaks. This is like a parent letting their kids run wild in a theme park with no supervision.

The Solution: Structured Concurrency

Kotlin coroutines promote a concept called structured concurrency. This means that new coroutines are launched within a specific CoroutineScope. This scope defines the lifecycle of the coroutines launched within it. When the scope is canceled, all the coroutines within that scope are also canceled. This creates a parent-child relationship, ensuring no coroutine is ever "lost" or orphaned.

Key Concepts:

  • CoroutineScope: Defines a scope for new coroutines. All coroutines launched within a scope are children of that scope.
  • CoroutineContext: A set of elements that define the behavior of a coroutine. It includes the Job and the CoroutineDispatcher, which determines the thread or threads the coroutine will run on.

Let's visualize it: Imagine you have a main task (the parent coroutine). This task can then launch several sub-tasks (child coroutines). With structured concurrency, if the main task is canceled, all its sub-tasks are automatically canceled as well.

kotlin
import kotlinx.coroutines.*

fun main() = runBlocking { // this: CoroutineScope
    launch { // launch a new coroutine in the scope
        delay(200L)
        println("Task from runBlocking")
    }

    coroutineScope { // Creates a new coroutine scope
        launch {
            delay(500L)
            println("Task from nested launch")
        }

        delay(100L)
        println("Task from coroutine scope") // This line will be printed before the nested launch
    }

    println("Coroutine scope is over") // This line is not printed until the nested scope completes
}

Here, runBlocking creates the top-level scope. The first launch is a child of this scope. coroutineScope creates a nested scope. The coroutine inside this nested scope must complete before the coroutineScope itself completes. This ensures that all the work within the scope is finished before moving on.

3. Exception Handling in Coroutines πŸ€•

The Problem: In the world of concurrency, things can and will go wrong. Network connections drop, files are not found, and unexpected errors occur. If an exception is thrown in one of your coroutines and not handled properly, it can crash your entire application.

The Solution: Coroutine Exception Handling

Coroutines provide a robust way to handle exceptions. The behavior depends on the coroutine builder used (launch vs. async).

  • launch: Exceptions are propagated up the parent-child hierarchy. If an exception is uncaught, it will eventually reach the root of the coroutine hierarchy and could terminate the application.
  • async: Exceptions are "deferred" and stored in the resulting Deferred object. They are only thrown when you call .await() on the Deferred.

The CoroutineExceptionHandler

For more centralized error handling, you can use a CoroutineExceptionHandler. This is a context element that you can add to your CoroutineScope to catch any uncaught exceptions.

Let's break down an example:

kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    val handler = CoroutineExceptionHandler { _, exception ->
        println("Caught $exception")
    }

    val job = GlobalScope.launch(handler) {
        throw AssertionError()
    }

    val deferred = GlobalScope.async(handler) {
        throw ArithmeticException() // Nothing is printed, relying on user to call await
    }

    joinAll(job, deferred)
}

In this example, the CoroutineExceptionHandler will catch the AssertionError from the launch block. However, it won't catch the ArithmeticException from the async block because the exception is held within the deferred object until await() is called.

Industry Practice: It's a common practice to use try-catch blocks within your coroutines for specific error handling and a global CoroutineExceptionHandler for logging and general error reporting.

4. Managing Shared State: Mutex and Thread-safe Data 🀝

The Problem: Imagine two people trying to write in the same notebook at the same time. The result would be a jumbled mess. This is what can happen when multiple coroutines try to access and modify the same data concurrently. This is known as a race condition and can lead to unpredictable and incorrect behavior.

The Solution: Synchronization

To prevent race conditions, you need to ensure that only one coroutine can access the shared state at a time. This is called mutual exclusion.

Mutex

Kotlin coroutines provide a Mutex (short for mutual exclusion) to protect shared resources. A Mutex has lock() and unlock() functions. Any code between these two calls is a "critical section" that only one coroutine can execute at a time.

mutex.withLock

The withLock extension function is the recommended way to use a Mutex. It automatically locks the mutex before executing the provided code block and unlocks it afterward, even if an exception occurs.

Let's see a practical example:

kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlin.system.measureTimeMillis

val mutex = Mutex()
var counter = 0

suspend fun massiveRun(action: suspend () -> Unit) {
    val n = 100  // number of coroutines to launch
    val k = 1000 // times an action is repeated by each coroutine
    val time = measureTimeMillis {
        coroutineScope { // scope for coroutines
            repeat(n) {
                launch {
                    repeat(k) { action() }
                }
            }
        }
    }
    println("Completed ${n * k} actions in $time ms")
}

fun main() = runBlocking {
    massiveRun {
        mutex.withLock {
            counter++
        }
    }
    println("Counter = $counter")
}

In this example, we launch 100 coroutines, and each one increments a shared counter 1000 times. Without the mutex.withLock, the final value of counter would be unpredictable due to race conditions. The Mutex ensures that the increment operation is atomic, guaranteeing the correct final count of 100,000.

Alternative to Mutex: For simpler cases like a counter, using thread-safe data structures from java.util.concurrent.atomic like AtomicInteger can be more efficient than a Mutex.


Extra Reading & References πŸ“š

Challenge

Challenge: Advanced Coroutine-based Download Manager

You are tasked with building a DownloadManager class in Kotlin that can handle multiple concurrent file downloads. This manager must be robust, handling failures gracefully and ensuring data integrity when updating shared state.

Requirements:

  1. Class Structure: Implement the DownloadManager class with the provided initial code.
  2. Structured Concurrency: All individual download coroutines must be launched within a single, managed parent scope. The startDownloads function should return the parent Job that oversees all the download tasks.
  3. Shared State Management: The manager tracks totalBytesDownloaded and a list of completedFiles. Access to these shared variables from multiple coroutines must be synchronized using a Mutex to prevent race conditions.
  4. Exception Handling: Create a CoroutineExceptionHandler to catch exceptions from download tasks. The handler should log or handle the error without crashing the entire DownloadManager or other ongoing downloads. To test this, your download simulation for any file named corrupt.dat should throw an IOException.
  5. Cancellation: Implement a cancelAll() method that can gracefully cancel all currently active download jobs. It should use the Job handles returned by the launch builder.
  6. Download Simulation: For each file, the download coroutine should simulate progress by using delay() and incrementally updating totalBytesDownloaded.

Expected result

Your completed DownloadManager class should correctly implement all the TODO sections.

  1. A Mutex instance is created and used via mutex.withLock { ... } whenever totalBytesDownloaded or completedFiles are accessed or modified.
  2. A CoroutineExceptionHandler is defined to catch exceptions. It should be correctly integrated into the context of the parent coroutine launched in startDownloads.
  3. The startDownloads method must use managerScope.launch with the handler to create a parent job. Inside it, it should loop through the files and launch a child coroutine for each, adding the returned Job to the activeJobs list.
  4. The logic for simulating downloads, including throwing an exception for corrupt.dat, must be correctly implemented inside the child coroutines.
  5. The cancelAll method must iterate through a copy of the activeJobs list (to avoid modification issues while iterating) and call .cancel() on each Job before clearing the list.
  6. The getStatus method must use the mutex to provide a thread-safe snapshot of the current download status.
kotlin

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.