Skip to content

Commit

Permalink
ram-unsafe-persist fix
Browse files Browse the repository at this point in the history
  • Loading branch information
bjsvedin committed Oct 4, 2023
1 parent 608f729 commit c090521
Showing 1 changed file with 18 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -20,19 +22,24 @@ class InMemoryUnsafePersistentFieldCollection<Model : Any>(
) : InMemoryFieldCollection<Model>(
data = Collections.synchronizedList(ArrayList()),
serializer = serializer
),
Closeable {
), Closeable{

private val scope = CoroutineScope(Dispatchers.IO)

@OptIn(ObsoleteCoroutinesApi::class)
val saveScope = scope.actor<Unit>(start = CoroutineStart.LAZY) {
handleCollectionDump()
}

init {
var closing = false
data.addAll(
encoding.decodeFromString(
ListSerializer(serializer),
file.takeIf { it.exists() }?.readText() ?: "[]"
)
)
val shutdownHook = Thread {
closing = true
this.close()
handleCollectionDump()
}
Runtime.getRuntime().addShutdownHook(shutdownHook)
this.signals.add {
Expand All @@ -41,6 +48,12 @@ class InMemoryUnsafePersistentFieldCollection<Model : Any>(
}

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)
Expand Down

0 comments on commit c090521

Please sign in to comment.