adds a mutex to make sure memory clearing only happens once at a time.

This commit is contained in:
Vitor Pamplona
2025-03-31 11:09:23 -04:00
parent 396831456c
commit b762907d69

View File

@@ -71,6 +71,7 @@ import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking import kotlinx.coroutines.runBlocking
import java.util.concurrent.atomic.AtomicBoolean
@Stable @Stable
class ServiceManager( class ServiceManager(
@@ -84,6 +85,8 @@ class ServiceManager(
private var collectorJob: Job? = null private var collectorJob: Job? = null
var isTrimmingMemoryMutex = AtomicBoolean(false)
private fun start(account: Account) { private fun start(account: Account) {
this.account = account this.account = account
start() start()
@@ -259,20 +262,26 @@ class ServiceManager(
} }
suspend fun trimMemory() { suspend fun trimMemory() {
LocalCache.cleanObservers() if (isTrimmingMemoryMutex.compareAndSet(false, true)) {
try {
LocalCache.cleanObservers()
val accounts = val accounts =
LocalPreferences.allSavedAccounts().mapNotNull { decodePublicKeyAsHexOrNull(it.npub) }.toSet() LocalPreferences.allSavedAccounts().mapNotNull { decodePublicKeyAsHexOrNull(it.npub) }.toSet()
account?.let { account?.let {
LocalCache.pruneOldAndHiddenMessages(it) LocalCache.pruneOldAndHiddenMessages(it)
NostrChatroomDataSource.clearEOSEs(it) NostrChatroomDataSource.clearEOSEs(it)
LocalCache.pruneHiddenMessages(it) LocalCache.pruneHiddenMessages(it)
LocalCache.pruneContactLists(accounts) LocalCache.pruneContactLists(accounts)
LocalCache.pruneRepliesAndReactions(accounts) LocalCache.pruneRepliesAndReactions(accounts)
LocalCache.prunePastVersionsOfReplaceables() LocalCache.prunePastVersionsOfReplaceables()
LocalCache.pruneExpiredEvents() LocalCache.pruneExpiredEvents()
}
} finally {
isTrimmingMemoryMutex.getAndSet(false)
}
} }
} }