realm-kotlin icon indicating copy to clipboard operation
realm-kotlin copied to clipboard

Eliminated notifier, writer and RealmReference to avoid memory leak

Open rorbech opened this issue 3 years ago • 2 comments

RealmReference introduced a cycle in the references, which seems to cause GC to fail deallocation the Realm and the RealmReference on native.

This draft PR is just my experiments of stripping the notifier and writer from Realm and then finally eliminating the realmReference in favor of a pure NativePointer in the BaseRealm. Just to show that this is in fact the triggering factor.

rorbech avatar Jun 27 '21 13:06 rorbech

Thinking a bit more about this at first it made sense, but we only store RealmReference as a WeakReference inside the Realm itself, so the cycle should be breakable 🤔 Something to look further into.

cmelchior avatar Jun 28 '21 18:06 cmelchior

We are only using weak references for the intermediate versions, as the current version must not be released until all objects and the realm are no longer referencing it.

Seems like the actual issue is that the cyclic reference is stored in a shared atomic reference. From https://blog.jetbrains.com/kotlin/2020/07/kotlin-native-memory-management-roadmap/:

Synchronization primitives must internally share a mutable state, which is supported in Kotlin/Native via special atomic references. Yet the existing memory management algorithm does not track cycles through such references.

rorbech avatar Jul 12 '21 08:07 rorbech

Closing as outdated as we have now moved on to the new memory model.

rorbech avatar Dec 12 '22 11:12 rorbech