Platform coroutines structured concurrency

From JetBrains/intellij-community · View interactive version

Platform coroutines structured concurrency is an AI agent skill from the GitHub repository JetBrains/intellij-community. Write or review IntelliJ coroutine scope ownership and cancellation.

How to use this skill

Skill file

<!-- Generated by community/.ai/render-guides.mjs; edit community/.agents/skills/platform-coroutines-structured-concurrency/SKILL.md -->

Coroutines: structured concurrency

Prefer standard primitives (coroutineScope, supervisorScope, a lifecycle-bound scope) over

hand-rolled scope wiring.

Related skill: kotlin-ui-swing-component-architecture (Swing UI and EDT ownership).

Deeper reading on the platform internals:

Cancellation,

Read-Write Lock.

dispatchers, read actions), docs/IntelliJ-Platform/4_man/Performance/ (freezes, background write actions)

and docs/IntelliJ-Platform/4_man/Indexes/ (the indexing system, dumb-aware code).

In Kotlin-Coroutines/, read especially 9_Gotchas-and-practices/ and 8_UI-EDT-Dispatchers.md.

Core review loop

  1. Name the owning CoroutineScope and the exact moment it is cancelled (Disposable disposal,

service teardown, explicit cancel()). If you cannot name that moment, that is the finding.

  1. Check long-running, CPU-bound, blocking, or looped coroutine bodies (and Flow collectors) for a

cooperative cancellation checkpoint — do not flag short bodies that already suspend.

  1. Check every catch on the path for a swallowed CancellationException / ProcessCanceledException.
  2. Check any invokeOnCompletion, GlobalScope, manual CoroutineScope(...), or launch in init

against the rules below, then classify (severity table) and propose the smallest structural fix.

Scope ownership and lifecycle

you). A standalone CoroutineScope(context) with no Job in the context gets a fresh root Job()

not linked to any parent — nothing cancels or awaits it, so it leaks:

```kotlin

// Wrong: detached root scope; cleanup depends on a manual cancel() that is easy to miss.

val scope = CoroutineScope(someContextElement.asContextElement())

// Right: child of an owning scope; cancelled structurally with its parent.

val scope = owner.coroutineScope.childScope("MyFeature", someContextElement.asContextElement())

```

owning Disposable (cancel the scope in dispose()) before launching any work, and verify that

registration actually runs.

its own Disposer registration, don't launch in init: the coroutine can run (touching a half-built

this) before registration completes and leak on failure — expose start() and call it after

Disposer.register. A @Service with an injected CoroutineScope is the exception: that scope

is cancelled with the service's container (app/project/plugin) by the platform — not via your

dispose(), and no Disposable is needed solely to cancel the injected scope — so a service

self-starting workers from init is acceptable. Just keep the constructor cheap and don't read

not-yet-initialized state.

when the result is genuinely owned for that whole lifetime.

ModalityState must be captured at the submit site, not at service/object construction. Avoid

CoroutineScope(ModalityState.defaultModalityState().asContextElement()); prefer

scope.launch(currentModality.asContextElement()) { ... } when modality belongs to that operation.

Modality dispatch semantics belong to kotlin-ui-swing-component-architecture.

Cooperative cancellation

suspension point (delay, yield), ensureActive(), or checkCanceled() in progress-aware code.

the resource in invokeOnCancellation.

blocking code, coroutineToIndicator { indicator -> ... }. Pair cancellation with an explicit

interrupt/close strategy; coroutine cancellation alone does not abort an in-progress blocking call.

Do not wrap blocking code in blockingContext: deprecated since 2024.2 because context is

installed implicitly (ReplaceWith("action()")).

Exception and failure propagation

scope out-of-band while launch returns normally, so try/runCatching sees nothing. To isolate a

child, use supervisorScope and handle the failure inside the child.

later failure — the exception surfaces at await(), and an unsupervised failure may already have

cancelled the parent before you await.

CancellationException too; swallowing it breaks structured concurrency and can hang cancellation.

ProcessCanceledException is a CancellationException subtype, so catching cancellation covers it

too. Rethrow cancellation first:

```kotlin

try {

body()

} catch (c: CancellationException) {

throw c

} catch (x: Throwable) {

handle(x)

}

```

If a coroutine owns an AsyncPromise or a callback result, cancellation can skip the normal result

path and leave external awaiters pending. In catch (c: CancellationException), complete the

external primitive (setError(c) / cancel) before throw c. Plain Deferred does not need this —

cancellation completes it.

Don't cancel yourself

Do not call cancel() on the coroutine you are currently running in — it does not stop execution

immediately (only at the next suspension point) and poisons the surrounding scope. Return early or

throw CancellationException. A shared suspend fun must never cancel its caller's job.

invokeOnCompletion

Prefer to avoid it. Three failure modes make it a trap:

  1. Runs concurrently, unordered, on an unspecified thread — not guaranteed on the EDT or after

your surrounding code. A check-then-act on a shared field races; use

AtomicReference.compareAndSet.

  1. Retained until the job completes — registering on a long-lived job (or in a loop) accumulates

handlers and leaks. Only register on short-lived jobs that actually finish.

  1. Must not throw — exceptions from handlers are reported through coroutine exception

handling/logging, not to the caller waiting for completion. Keep the body to trivial, non-failing

bookkeeping.

Preferred alternative — do completion work as the last step inside the coroutine:

scope.launch {
  try { doWork() }
  finally { withContext(NonCancellable + Dispatchers.EDT) { onFinished() } }
}

Use NonCancellable only for small, bounded cleanup that must run even after cancellation — never

wrap substantial work in it, and keep UI cleanup lifecycle/disposal-guarded (do not touch a disposed

component). Cancelling an already-completed Job is a no-op, so "clear my job handle on completion"

bookkeeping is often unnecessary — verify it changes behavior before adding it.

Severity defaults

Adjust for actual impact.

| Pattern | Default | Smallest fix |

|---|---|---|

| GlobalScope for feature work | Critical | child of a lifecycle scope |

| Detached CoroutineScope never cancelled | Critical | childScope of an owning scope |

| Swallowed CancellationException/ProcessCanceledException | Critical | rethrow cancellation before catch (Throwable) |

| Non-cooperative infinite/long loop | Critical | add ensureActive()/yield/suspension point |

| runCatching/try around launch/async to contain failure | Critical | supervisorScope + handle inside child |

| launch in init with a scope tied to own Disposer registration | Major | start() after registration |

| Manual scope where childScope fits; scope not tied to lifecycle | Major | inject/childScope; register Disposable before launch |

| invokeOnCompletion mutating shared state unsynchronized or that can throw | Major | compareAndSet, or clean up in coroutine finally |

| Self-cancellation (cancel() on current job) | Major | return / throw CancellationException |

| Promise/callback bridge left pending on cancellation | Major | complete/cancel external primitive before rethrow |

| Unnecessary invokeOnCompletion bookkeeping | Minor | remove it |

| blockingContext wrapper | Minor | delete the wrapper |

| Cancellation reported as a user-visible error | Minor | rethrow silently |

| supervisorScope/SupervisorJob where a plain scope suffices | Minor | use coroutineScope |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.