Skip to content

Memory leak when dropping waker after runtime drop #489

@Paraworker

Description

@Paraworker

Consider the following case:

static WAKER: AtomicWaker = AtomicWaker::new();

struct LeakWatcher;

impl Future for LeakWatcher {
    type Output = ();

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
        WAKER.register(cx.waker());
        Poll::Pending
    }
}

impl Drop for LeakWatcher {
    fn drop(&mut self) {
        println!("LeakWatcher is being dropped!!!");
    }
}

fn test_memory_leak() {
    let rt = Runtime::new().unwrap();

    rt.block_on(async {
        runtime::spawn(LeakWatcher).detach();
    });

    // Dropping the runtime clears all runnables in the queue, which breaks the reference cycle.
    drop(rt);

    // Dropping the waker after the runtime is dropped may push the runnable back into the queue,
    // recreating the reference cycle.
    let _ = WAKER.take();
}

Using Weak in the schedule closure might be necessary.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions