     /// - Parameter spaceId: The id of the space.
     /// - Returns: A MXSpace with the associated roomId or null if room doesn't exists or the room type is not space.
     public func getSpace(withId spaceId: String) -> MXSpace? {
-        var space = self.spacesPerId[spaceId]
+        var space: MXSpace?
+        spacesPerIdReadWriteQueue.sync(flags: .barrier) {
+           space = self.spacesPerId[spaceId]
+        }
         if space == nil, let newSpace = self.session.room(withRoomId: spaceId)?.toSpace() {
             space = newSpace
-            self.spacesPerId[spaceId] = newSpace
+            spacesPerIdReadWriteQueue.sync(flags: .barrier) {
+                self.spacesPerId[spaceId] = newSpace
+            }
         }
         return space
     }

                    self.prepareData(with: roomIds, index: index+1, output: output, completion: completion)
                    return
                }
                
                let space = self.spacesPerId[room.roomId] ?? room.toSpace()
                
                self.prepareData(with: roomIds, index: index, output: output, room: room, space: space, isRoomDirect: room.isDirect, directUserId: room.directUserId, completion: completion)
            }

public class MXSpaceService: NSObject {

    // MARK: - Properties

    private let spacesPerIdReadWriteQueue: DispatchQueue = {
      let label = "org.matrix.sdk.MXSpaceService.spacesPerIdReadWriteQueue"
      return DispatchQueue(label: label, attributes: .concurrent)
    }()

    private unowned let session: MXSession
    
    private lazy var stateEventBuilder: MXRoomInitialStateEventBuilder = {
