Using inMemory realm with concurrency

Hi,

I basically gave up on trying to solve this issue with Realm Failed to open file at path '....default.realm.lock': Operation not permitted

So I am trying in this mode to use InMemoryIdentifier and to work on memory for this case.

I learned that in InMemory state I must hold a strong reference to the realm instance, but that’s a problem in a concurrent usage. So what can I do in this case?

I tried this:

static private let queue = DispatchQueue.init(label: "realm.queue")
    
    static private var realm: Realm = {
      return try! Realm(configuration: configuration, queue: queue)
    }()`

but it crashes immediately.

Any ideas?
Thanks…!

To handle concurrency with Realm’s in-memory database, ensure each thread gets its own Realm instance. Since Realm instances aren’t thread-safe, create a new instance on each thread using a function with a unique inMemoryIdentifier. This allows multiple instances to share data in memory while maintaining thread safety. Use a concurrent DispatchQueue to manage access, creating a fresh instance of Realm for each operation. This approach balances memory usage and thread safety, reducing crashes due to concurrent access.

1 Like