diff --git a/shared_realm.cpp b/shared_realm.cpp index 6d57f111..c87dd5d4 100644 --- a/shared_realm.cpp +++ b/shared_realm.cpp @@ -374,6 +374,22 @@ uint64_t Realm::get_schema_version(const realm::Realm::Config &config) return ObjectStore::get_schema_version(Realm(config).read_group()); } +void Realm::close() +{ + invalidate(); + + if (m_notifier) { + m_notifier->remove_realm(this); + } + + m_group = nullptr; + m_shared_group = nullptr; + m_history = nullptr; + m_read_only_group = nullptr; + m_notifier = nullptr; + m_binding_context = nullptr; +} + SharedRealm RealmCache::get_realm(const std::string &path, std::thread::id thread_id) { std::lock_guard lock(m_mutex); @@ -446,6 +462,13 @@ void RealmCache::cache_realm(SharedRealm &realm, std::thread::id thread_id) void RealmCache::clear() { std::lock_guard lock(m_mutex); + for (auto const& path : m_cache) { + for (auto const& thread : path.second) { + if (auto realm = thread.second.lock()) { + realm->close(); + } + } + } m_cache.clear(); } diff --git a/shared_realm.hpp b/shared_realm.hpp index e6c94fc2..81b14bf7 100644 --- a/shared_realm.hpp +++ b/shared_realm.hpp @@ -101,6 +101,10 @@ namespace realm { std::thread::id thread_id() const { return m_thread_id; } void verify_thread() const; + // Close this Realm and remove it from the cache. Continuing to use a + // Realm after closing it will produce undefined behavior. + void close(); + ~Realm(); private: