Sub topic 8
Cleaning up when a future is dropped
This chapter assumes you know Rust ownership and the Drop trait, async/await basics, and how to use #[tokio::main] and tokio::spawn. Earlier chapters showed that cancelling a future means dropping it. Here we look at what that drop does to the state the future holds.
What gets dropped
An async fn compiles to a state machine. Every local variable that is alive across an .await is stored inside that state machine. When the future is dropped, Rust drops the stored locals in reverse order of declaration, just as it does when a function returns. Code written after the pending .await never runs.
The example below uses a timeout to cancel work while it sleeps.
use std::time::Duration;
use tokio::time::{sleep, timeout};
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("dropping {}", self.0);
}
}
async fn work() {
let _guard = Noisy("work state");
sleep(Duration::from_secs(10)).await;
println!("never printed");
}
#[tokio::main]
async fn main() {
let _ = timeout(Duration::from_millis(50), work()).await;
println!("after timeout");
}The output is:
dropping work state
after timeoutThe guard is dropped when the timeout fires, so "dropping work state" appears before "after timeout". The line "never printed" does not appear.
Drop guards
Because locals are dropped on cancellation, a type with a Drop implementation is the right place for cleanup. This is called a drop guard. Use one for anything that must be undone if the future stops early, such as removing an entry from a shared map, decrementing a counter, or releasing a lock.
Many standard and Tokio types already work this way. A MutexGuard unlocks when dropped, a Sender closes its side of the channel when the last clone is dropped, and a permit returns to its semaphore. You get correct cleanup for free if you hold resources in values like these.
The limits of Drop
Drop::drop is a synchronous function. You cannot .await inside it. This matters when cleanup needs async work, such as sending a goodbye message over a network connection or flushing a buffer to a socket.
You have three common options:
- Make the cleanup synchronous. Many resources can be released without awaiting.
- Spawn the cleanup from
dropwithtokio::spawn. This only works if the runtime is still running, and the cleanup is not guaranteed to finish before the program exits. - Avoid relying on drop for async cleanup. Use cooperative cancellation instead, so the task sees a signal and runs its async cleanup on a normal code path. The
CancellationTokenchapter covers this.
Cleanup that must not be skipped
A common bug is a cleanup step placed at the end of an async function.
use std::time::Duration;
use tokio::time::sleep;
async fn handle_request(active: &std::sync::atomic::AtomicUsize) {
active.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
sleep(Duration::from_secs(1)).await;
// Skipped if the future is dropped during the sleep.
active.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
}If a timeout drops this future during the sleep, the counter is incremented but never decremented. The fix is a guard whose Drop performs the decrement, so it runs on both normal completion and cancellation.
Summary of the rules
| Situation | What runs |
|---|---|
| Future completes normally | All code, then locals are dropped |
| Future dropped at an await | Only `Drop` implementations of live locals |
| Cleanup needs `.await` | Not possible in `Drop`; use a token or spawn |
Exercise
A function increments a shared counter, awaits a network call, then decrements the counter on the last line. The caller wraps it in timeout. What goes wrong when the timeout fires, and how do you fix it?
Show answer
The future is dropped at the await, so the decrement never runs and the counter stays too high. Fix it by creating a guard struct after the increment whose Drop implementation decrements the counter. Drop runs on both normal completion and cancellation.