Sub topic 9
Spawned tasks: abort, detach, and JoinError
This chapter assumes you know the following:
- Dropping a future cancels it at its current await point.
tokio::spawnruns a future as an independent task.- Basic
Resultmatching.
Earlier chapters cancelled futures that you own, such as the one inside timeout or a select! branch. A spawned task is different. The runtime owns its future, and you hold only a JoinHandle. This chapter covers what that handle can and cannot do.
What a JoinHandle represents
tokio::spawn returns a JoinHandle<T>. The handle is a claim ticket for the task's result. It is not the task itself, so dropping it does not drop the future.
| Action on the handle | Effect on the task |
|---|---|
| `handle.await` | Waits for the task and returns `Result<T, JoinError>` |
| `drop(handle)` | Detaches the task. It keeps running, and its result is discarded |
| `handle.abort()` | Asks the runtime to cancel the task |
This differs from a plain future, where dropping is the cancellation. For a spawned task, dropping the handle does the opposite and lets the task run on without you.
Detaching: dropping the handle
The task below keeps running after its handle is gone.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
sleep(Duration::from_millis(50)).await;
println!("detached task finished");
});
drop(handle);
// Keep the runtime alive long enough for the task to finish.
sleep(Duration::from_millis(100)).await;
}The program prints detached task finished. Detached tasks are convenient for fire-and-forget work, but they have two costs:
- Nobody observes a panic. The panic message goes to stderr, and the task simply ends.
- Nothing stops the task. If it loops forever, it runs until the runtime shuts down.
When the runtime shuts down, for example when main returns from #[tokio::main], all remaining tasks are dropped at their next await point. A detached task is therefore not guaranteed to finish. In the example above, the final sleep is what gives the task time to run.
Aborting a task
JoinHandle::abort requests cancellation. It does not stop the task immediately. It marks the task as cancelled, and the runtime drops the task's future the next time the task is scheduled. This is the same drop-at-an-await-point model as before, applied from outside.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
sleep(Duration::from_secs(10)).await;
});
handle.abort();
let err = handle.await.unwrap_err();
assert!(err.is_cancelled());
println!("task was cancelled");
}Three details matter here:
aborttakes&selfand returns immediately. It does not wait for the task to stop.- Awaiting the handle afterwards is how you wait. The handle resolves only after the future has been dropped.
abortconsumes nothing, so you can still await the handle. Awaiting a cancelled task yieldsErr(JoinError).
Waiting for cleanup
Because the handle resolves after the drop, you can use it to be sure that destructors have run.
use std::time::Duration;
use tokio::time::sleep;
struct Guard(&'static str);
impl Drop for Guard {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
#[tokio::main]
async fn main() {
let handle = tokio::spawn(async {
let _guard = Guard("worker state");
sleep(Duration::from_secs(10)).await;
println!("never printed");
});
// Give the task a chance to start and reach its await point.
sleep(Duration::from_millis(50)).await;
handle.abort();
let _ = handle.await;
println!("handle resolved");
}The output is dropping worker state followed by handle resolved. If you called abort and then did not await the handle, the guard's Drop would still run, but you would have no way to know when.
Abort is a race, not a guarantee
If the task has already finished, abort does nothing and the handle returns Ok(value). The same happens if the task finishes before the runtime processes the abort. Do not assume that calling abort means you will see is_cancelled(). Always handle both outcomes.
Abort cannot interrupt code that never awaits
An aborted task stops only when it yields at an await point. Two cases ignore abort:
- An async task stuck in a long synchronous loop or a blocking call never reaches an await. The abort stays pending until it does.
- A closure running under
tokio::task::spawn_blockingcannot be aborted once it has started.abortonly works if the closure has not begun running yet.
The chapter on blocking code returns to this. For now, remember that abort is cooperative at the await level.
JoinError: reading the result
JoinError has two causes, and you can tell them apart.
| How the task ended | `handle.await` returns | Useful methods |
|---|---|---|
| Returned normally | `Ok(value)` | None |
| Panicked | `Err(e)` | `e.is_panic()`, `e.into_panic()` |
| Aborted, or dropped by runtime shutdown | `Err(e)` | `e.is_cancelled()` |
A complete handler distinguishes all three.
use std::time::Duration;
use tokio::time::sleep;
#[tokio::main]
async fn main() {
let finishes = tokio::spawn(async { 42_i32 });
let panics = tokio::spawn(async {
let missing: Option<i32> = None;
missing.expect("boom")
});
let aborted = tokio::spawn(async {
sleep(Duration::from_secs(10)).await;
1_i32
});
aborted.abort();
let handles = [("finishes", finishes), ("panics", panics), ("aborted", aborted)];
for (name, handle) in handles {
match handle.await {
Ok(value) => println!("{name}: returned {value}"),
Err(e) if e.is_cancelled() => println!("{name}: cancelled"),
Err(e) if e.is_panic() => {
let payload = e.into_panic();
let message = payload
.downcast_ref::<&str>()
.map(|s| s.to_string())
.or_else(|| payload.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "unknown panic".to_string());
println!("{name}: panicked with {message:?}");
}
Err(e) => println!("{name}: failed: {e}"),
}
}
}The panic message also appears on stderr when the panic happens, which is normal. A panic inside a spawned task does not take down the process or the runtime. It is confined to that task and reported through the handle. You can use e.into_panic() with std::panic::resume_unwind if you want to re-raise it in the awaiting task.
A common mistake is handle.await.unwrap(). It turns both a panic and a deliberate abort into a panic in the caller. Use it only when a failure of the task really should crash the caller.
Which outcomes you can observe
Aborting many tasks
If you need to cancel from a place that does not own the JoinHandle, call handle.abort_handle(). It returns an AbortHandle. This is a cloneable value that can abort the task but cannot await its result.
For groups of tasks, use tokio::task::JoinSet. It owns its tasks and cleans them up.
use std::time::Duration;
use tokio::{task::JoinSet, time::sleep};
#[tokio::main]
async fn main() {
let mut set = JoinSet::new();
for i in 0..3_i32 {
set.spawn(async move {
sleep(Duration::from_secs(10)).await;
i
});
}
set.abort_all();
while let Some(result) = set.join_next().await {
match result {
Ok(i) => println!("task {i} finished"),
Err(e) => println!("cancelled: {}", e.is_cancelled()),
}
}
}JoinSet has one property that raw handles lack: dropping the set aborts every task in it. Dropping a bare JoinHandle detaches, but dropping a JoinSet cancels. This makes it a good default when a group of tasks should not outlive the code that started them. It also means a task that you spawned into a JoinSet and then forgot about will vanish when the set goes out of scope.
Choosing between abort and the alternatives
abort is blunt. The task gets no chance to run code after its current await point, apart from destructors. That is fine for work that is safe to discard, such as a cache refresh or a speculative request.
It is a poor fit when the task is in the middle of something that must complete in a consistent way, such as writing a record in two steps or acknowledging a message. For those tasks, use a CancellationToken, which lets the task decide where to stop. If a task must run cleanup code that awaits, that code cannot live in a destructor, because Drop cannot be async. The cooperative approach handles that case.
A rule of thumb:
- Use
abortwhen dropping the task's state at any await point is acceptable. - Use a token when the task needs to finish its current step or run async cleanup.
- Use
JoinSetwhen you want the group's lifetime tied to a scope.
Common errors
- Assuming
drop(handle)stops the task. It detaches the task, which keeps running. Callabortif you want it stopped. - Calling
abortand moving on. The task may still be running destructors. Await the handle if later code depends on the cleanup having finished. - Treating
Erras always meaning panic. Checkis_cancelled()andis_panic(). An aborted task is not a bug. - Expecting abort to stop a busy loop. Without an await point, the task cannot be dropped.
- Relying on detached tasks at shutdown. When the runtime exits, tasks are dropped without a chance to finish.
Exercise
You spawn a task with let h = tokio::spawn(work());. Later, two different code paths run: one calls drop(h), the other calls h.abort() followed by h.await. What happens to work() in each case, and what does the second path's await return if work() had already completed?
Show answer
After drop(h), the task is detached and keeps running to completion, with its result discarded. After h.abort(), the runtime drops the future at its next await point, running destructors, and h.await returns Err(JoinError) with is_cancelled() true. If work() had already completed, abort has no effect and h.await returns Ok(value).
Exercise
A spawned task holds a guard whose Drop prints a message, then loops on std::thread::sleep(Duration::from_millis(10)) with no .await. You call handle.abort() and then handle.await. Does the await return promptly? Why or why not?
Show answer
No. The task never reaches an await point, so the runtime cannot drop its future and the abort stays pending. The handle.await waits for as long as the loop runs. The fix is to use tokio::time::sleep(...).await inside the loop, or to move the blocking work to spawn_blocking and stop it with a flag or token that it checks itself.