Skip to content

Commit

Permalink
fix(ui): Replace the RwLock by a Mutex in RoomListService::rooms.
Browse files Browse the repository at this point in the history
This patch replaces the `RwLock` by a `Mutex` in
`RoomListService::rooms` because:

1. it removes a race condition,
2. `RwLock` was used because the lock could have been taken for a long
   time due to the previous `.await` point. It's no longer the case, so we
   can blindly use a `Mutex` here.
  • Loading branch information
Hywan committed Jun 13, 2024
1 parent edec6e7 commit a7ff058
Showing 1 changed file with 8 additions and 9 deletions.
17 changes: 8 additions & 9 deletions crates/matrix-sdk-ui/src/room_list_service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ mod state;
use std::{
future::ready,
num::NonZeroUsize,
sync::{Arc, RwLock},
sync::{Arc, Mutex as StdMutex},
time::Duration,
};

Expand Down Expand Up @@ -114,7 +114,7 @@ pub struct RoomListService {
state: SharedObservable<State>,

/// Room cache, to avoid recreating `Room`s every time users fetch them.
rooms: Arc<RwLock<RingBuffer<Room>>>,
rooms: Arc<StdMutex<RingBuffer<Room>>>,

/// The current viewport ranges.
///
Expand Down Expand Up @@ -204,7 +204,7 @@ impl RoomListService {
client,
sliding_sync,
state: SharedObservable::new(State::Init),
rooms: Arc::new(RwLock::new(RingBuffer::new(Self::ROOM_OBJECT_CACHE_SIZE))),
rooms: Arc::new(StdMutex::new(RingBuffer::new(Self::ROOM_OBJECT_CACHE_SIZE))),
viewport_ranges: Mutex::new(vec![VISIBLE_ROOMS_DEFAULT_RANGE]),
})
}
Expand Down Expand Up @@ -427,17 +427,16 @@ impl RoomListService {

/// Get a [`Room`] if it exists.
pub fn room(&self, room_id: &RoomId) -> Result<Room, Error> {
{
let rooms = self.rooms.read().unwrap();
let mut rooms = self.rooms.lock().unwrap();

if let Some(room) = rooms.iter().rfind(|room| room.id() == room_id) {
return Ok(room.clone());
}
if let Some(room) = rooms.iter().rfind(|room| room.id() == room_id) {
return Ok(room.clone());
}

let room = Room::new(&self.client, room_id, &self.sliding_sync)?;

self.rooms.write().unwrap().push(room.clone());
// Save for later.
rooms.push(room.clone());

Ok(room)
}
Expand Down

0 comments on commit a7ff058

Please sign in to comment.