Explicit Dropping Of HashMap

I have a loop to fetch a new set of data, which will be inserted into a HashMap. Instead of clearing the old HashMap I have decided to go with allocating a brand new one and drop the previous.

Is what I'm doing actually safe and not leaking memory? My understanding is that I don't have to do an explicit drop the clear hashmap

#[derive(Clone, Deserialize)]
pub struct Message {
    name: String,
    data: String
}

pub struct Inbox {
    data: Arc<Mutex<HashMap<String, Message>>>,
}

impl ChaosOracle {

    pub fn get_message(self, id: &str) -> Option<Message> {
        self.data.lock().unwrap().get(id).cloned()
    }

    pub fn fetch_messages_loop(&self, http_client: Client) {
        let http_client = http_client.clone();
        let data = self.data.clone();

        tokio::spawn(async move {
            loop {
                if let Ok(new_result) = get_message(&http_client).await {
                    *data.lock().unwrap() = map_to_struct(&new_result);
                }

                sleep(Duration::from_millis(2000)).await
            }
        });
    }
}

Yes, this will not cause a leak. And it is "safe" using the Rust definition, since you have not used the unsafe keyword.

When you assign to a variable, the variable's previous value is dropped. Also, variables are dropped when they go out of scope, and the values behind ref counted smart pointers (Rc, Arc, etc) are dropped when their ref count reaches zero.

Also note:

  • In safe code, it is possible to accidentally leak memory by creating a reference cycle. I don't know of other ways to accidentally leak in safe code.
  • In safe code you can explicitly leak memory when you want something to stay allocated for the duration of the program. This gives the leaked value a 'static lifetime.
  • In unsafe code, there are multiple ways to accidentally (or intentionally) leak memory, since Rust's safeguards are off.
4 Likes

You can also start a “short-lived” background thread that deadlocks or otherwise fails to terminate.

2 Likes

Thanks for answering!