Structured Concurrency & Cancellation Interview Questions
KOTLIN › Coroutines
What is structured concurrency, and why does it matter?
What a strong answer covers: Every coroutine is launched in a scope and becomes a child of that scope's Job. A parent waits for its children, cancelling the parent cancels all children, and a child's failure propagates up. That means no coroutine is lost or leaked, work is tied to a lifecycle like viewModelScope, and errors aren't silently swallowed.
How does cancellation work in coroutines? Why is it called cooperative?
What a strong answer covers: Cancelling a Job marks it cancelled and the coroutine only stops at suspension points that check for it, like delay, withContext, yield, or most kotlinx functions, which throw CancellationException. A tight CPU loop that never suspends keeps running unless it checks isActive or calls ensureActive() or yield(). Blocking calls like Thread.sleep don't respond to cancellation at all.
What is the difference between coroutineScope and supervisorScope?
What a strong answer covers: coroutineScope waits for all children and if any child fails it cancels the rest and rethrows: all or nothing. supervisorScope also waits for children, but one child's failure doesn't cancel its siblings or the scope, so each child handles its own errors. Use supervisorScope when tasks are independent, like loading separate widgets on a dashboard.
Why should you never swallow CancellationException, and how can catching Exception break cancellation?
What a strong answer covers: CancellationException is how a coroutine learns it should stop. A try { } catch (e: Exception) around a suspend call catches it too, so the coroutine carries on as if nothing happened, possibly updating state for a screen that's gone. Fix: rethrow it (catch CancellationException first and rethrow), call ensureActive(), or catch only the specific exceptions you expect. runCatching has the same problem.
You need to run cleanup, like closing a resource or writing to a database, when a coroutine is cancelled. How do you do it safely, and why can't you just call a suspend function in finally?
What a strong answer covers: Use try/finally: finally runs on cancellation. But the coroutine is already cancelled, so any suspend call in finally throws CancellationException immediately. Wrap suspending cleanup in withContext(NonCancellable) { }. Keep it short, because it delays cancellation. For non-suspending cleanup like closing a stream, use .use { } or plain finally. Also cover work that must outlive the screen: use an application-scoped CoroutineScope or WorkManager instead.