The problem is that this line:
App::new()
.data(Mutex::new(AppState { dog_map: dog_map.clone() }))
clones the HashMap each time a new thread is created, so you end up with n
threads that each have their own separate sets of dogs. An update or creation on one thread will not be seen by the other threads.
Instead, you'll want to make sure that you have a single HashMap, and only clone pointers to it. You could do this by wrapping your state in Arc<T>
, but this isn't necessary since Data<T>
is already a wrapper for Arc<T>
. Instead you can create a Data<Mutex<AppState>>
outside the closure, clone it inside the closure, and pass it to app_data()
instead of data()
:
let data = web::Data::new(Mutex::new(AppState { dog_map }));
HttpServer::new(move || {
App::new()
.app_data(data.clone()) // note: `app_data`, not `data`
// ...
}
For more details, see the Data
and App::data
docs.