diff --git a/server-core/src/main/kotlin/com/lightningkite/lightningdb/InMemoryUnsafePersistentFieldCollection.kt b/server-core/src/main/kotlin/com/lightningkite/lightningdb/InMemoryUnsafePersistentFieldCollection.kt index 6c8cf566..b30f82ab 100644 --- a/server-core/src/main/kotlin/com/lightningkite/lightningdb/InMemoryUnsafePersistentFieldCollection.kt +++ b/server-core/src/main/kotlin/com/lightningkite/lightningdb/InMemoryUnsafePersistentFieldCollection.kt @@ -1,5 +1,7 @@ package com.lightningkite.lightningdb +import kotlinx.coroutines.* +import kotlinx.coroutines.channels.actor import kotlinx.serialization.KSerializer import kotlinx.serialization.StringFormat import kotlinx.serialization.builtins.ListSerializer @@ -20,10 +22,16 @@ class InMemoryUnsafePersistentFieldCollection( ) : InMemoryFieldCollection( data = Collections.synchronizedList(ArrayList()), serializer = serializer -), - Closeable { +), Closeable{ + + private val scope = CoroutineScope(Dispatchers.IO) + + @OptIn(ObsoleteCoroutinesApi::class) + val saveScope = scope.actor(start = CoroutineStart.LAZY) { + handleCollectionDump() + } + init { - var closing = false data.addAll( encoding.decodeFromString( ListSerializer(serializer), @@ -31,8 +39,7 @@ class InMemoryUnsafePersistentFieldCollection( ) ) val shutdownHook = Thread { - closing = true - this.close() + handleCollectionDump() } Runtime.getRuntime().addShutdownHook(shutdownHook) this.signals.add { @@ -41,6 +48,12 @@ class InMemoryUnsafePersistentFieldCollection( } override fun close() { + scope.launch { + saveScope.send(Unit) + } + } + + fun handleCollectionDump() { val temp = file.parentFile!!.resolve(file.name + ".saving") temp.writeText(encoding.encodeToString(ListSerializer(serializer), data.toList())) Files.move(temp.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE)