Sub topic 3
Cleaning Up When a Future Is Dropped
Assume basic Rust ownership, Drop, async/await, Tokio tasks, and mpsc channels. In async Rust, cancellation usually means dropping a future. A dropped future stops being polled, so its local values are dropped too.
Cleaning Up on Cancellation
Use a Drop guard for cleanup that must happen when work ends early:
struct ResourceGuard(&'static str);
impl Drop for ResourceGuard {
fn drop(&mut self) {
println!("released {}", self.0);
}
}
async fn work() {
let _guard = ResourceGuard("connection");
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
println!("work completed");
}If work() is dropped during sleep, the guard is dropped and the cleanup message is printed. Code after the await point does not run.
Spawned Tasks: Abort and Detach
A spawned task owns its future independently of the caller. Calling JoinHandle::abort requests cancellation. Awaiting the handle reports a cancelled JoinError.
let handle = tokio::spawn(async {
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
});
handle.abort();
match handle.await {
Err(error) if error.is_cancelled() => println!("task cancelled"),
result => println!("task result: {result:?}"),
}Dropping the JoinHandle detaches the task. The task keeps running, but the caller no longer receives its result or errors.
Cooperative Cancellation with `CancellationToken`
A CancellationToken lets a task check for shutdown and leave voluntarily.
use tokio::time::{sleep, Duration};
use tokio_util::sync::CancellationToken;
async fn worker(token: CancellationToken) {
loop {
tokio::select! {
_ = token.cancelled() => break,
_ = sleep(Duration::from_millis(50)) => {
println!("one unit completed");
}
}
}
}Graceful Shutdown
A graceful shutdown signals workers, waits for them, and then releases shared resources.
Create child tokens for workers, call cancel on the parent, then await every JoinHandle.
Why Blocking Code Ignores Your Timeout
Tokio timeouts cancel futures by dropping them. They cannot interrupt synchronous blocking code such as a long loop or std::thread::sleep. Blocking the runtime thread also prevents Tokio's timer from being polled. Move blocking work to spawn_blocking, or use an interruptible async operation.
Testing Paused Time
Enable Tokio's test-util feature and use paused time:
#[tokio::test(start_paused = true)]
async fn times_out() {
use std::time::Duration;
use tokio::time::{sleep, timeout};
let result = timeout(Duration::from_secs(1), sleep(Duration::from_secs(60))).await;
assert!(result.is_err());
}The test clock advances while the runtime is idle, so the test runs quickly and deterministically.
Exercise
What happens to a local Drop guard when a future is cancelled?
Show answer
The guard is dropped, so its Drop implementation runs.