Skip to content

How to create a async HashMap singleton #3359

Answered by Darksonn
leenux asked this question in Q&A
Discussion options

You must be logged in to vote

The shared state chapter in the Tokio tutorial covers this. As for making it a global variable, you can do this with lazy_static!.

use std::sync::Mutex;
use std::collections::HashMap;

lazy_static! {
    static ref MY_SINGLETON: Mutex<HashMap<String, String>> = Mutex::new(HashMap::new());
}

Note that when using lazy_static!, you do not need an Arc. The purpose of an Arc is to share the variable, but we already get this from lazy_static!.

Note also that you should not be using an tokio::sync lock for this, but rather an std::sync lock. Please read the shared state chapter that I linked for an explanation of why. As for RwLock vs Mutex, you should prefer a Mutex, and if that doesn't do the …

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@leenux
Comment options

@Darksonn
Comment options

Answer selected by leenux
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants