Async Operations · 20 min · free lesson

Own Tasks with JoinSet

Keep the tasks you start in a collection whose lifetime and results are explicit.

Core idea

Spawning starts an independent task; awaiting its result is a separate responsibility.

Diagram for Own Tasks with JoinSet: a Rust code example flows to the lesson rule and the key observation.
Completion order, errors, and task lifetime

Understand it

An async function creates a future, while spawning places that future under a runtime's scheduler. If your operation starts several child tasks, decide who owns their handles and who observes failures. JoinSet groups tasks returning the same type and yields their results in completion order. That order is not necessarily the order in which the tasks were inserted.

The example associates each result with its input index, drains the set with join_next, and sorts the collected pairs before presenting them. The sorting is a deliberate presentation policy, not an assumption about scheduler order. Handle the outer JoinError separately from any application Result returned inside a task: a task panic and a rejected input are different failures.

Dropping a JoinSet aborts its remaining tasks. This makes ownership visible, but abort is not a business-level rollback and does not undo effects already performed. A spawned blocking operation can have additional cancellation limitations. A reliable operation either drains its children, cancels them according to an explicit policy, or transfers their ownership to a longer-lived component.

For practice, make one child return an application error without panicking. Then make a different child panic and compare the two error layers. Do not require an exact completion sequence in the test; verify the set of indexed results. Keep real network work out of this exercise so scheduling behavior is not confused with a server or a backend execution service.

Local Cargo profile: open the supplied project in Crabrix or the browser Playground. Explicitly prepare its pinned Cargo packages once on each device, then Run and Debug compile and execute on that device without a backend. The project includes Cargo.lock. The lesson question remains the completion exercise; running an unchanged demonstration does not prove a separate programming challenge. Tokio 1.54.1 is built with default-features=false and only rt/sync. The current-thread builder needs no runtime attribute macro. JoinSet, Semaphore, watch and yield_now are real Tokio APIs. This profile supplies cooperative concurrency, not native threads, sockets, OS signals or CPU parallelism.

Read the code

use tokio::{runtime::Builder, task::JoinSet};
fn main() {
    let rt = Builder::new_current_thread()
        .build()
        .unwrap();
    rt.block_on(async {
        let mut tasks = JoinSet::new();
        for n in 0..4 {
            tasks.spawn(async move { (n, n * n) });
        }
        let mut results = Vec::new();
        while let Some(result) =
            tasks.join_next().await
        {
            results.push(result.unwrap());
        }
        results.sort_unstable();
        assert_eq!(
            results,
            [(0, 0), (1, 1), (2, 4), (3, 9)]
        );
    });
    println!("joinset-task-ownership: ok");
}

Completion order, errors, and task lifetime

Open local example in Playground ↗

Try it

Run the declared desktop Cargo example. Add a Result-valued task and handle application errors independently from JoinError. Open the supplied local Cargo project, prepare packages, then Run or Debug it. Change inputs and examine the assertions. Answer the lesson question separately.

What success looks like: JoinSet yields completed tasks. Preserve an index if the application needs a stable presentation order.

Check your understanding

In which order does JoinSet yield completed tasks?

Reveal the answer
  1. Insertion order in every runtime
  2. Completion order, which may differ from insertion order
  3. Always sorted by return value

JoinSet yields completed tasks. Preserve an index if the application needs a stable presentation order.

Go deeper

Common misconception: Dropping every task handle is a graceful shutdown protocol.

An explicit owner must decide whether to wait, request cancellation, or abort; prior effects are not rolled back.

  1. Start: Keep task ownership in one JoinSet.
  2. Observe: Distinguish JoinError from application errors.
  3. Finish: Drain results or explicitly cancel remaining tasks.

Transfer challenge: Document what happens when one task fails after another has written a report. Do not describe abort as rollback.

Connections

  • Bound Work Before Spawning: Semaphore permits and bounded queues