diff --git a/server/src/main/kotlin/org/ivdnt/galahad/FileBackedValue.kt b/server/src/main/kotlin/org/ivdnt/galahad/FileBackedValue.kt index 5eb7262..791b1e8 100644 --- a/server/src/main/kotlin/org/ivdnt/galahad/FileBackedValue.kt +++ b/server/src/main/kotlin/org/ivdnt/galahad/FileBackedValue.kt @@ -2,6 +2,9 @@ package org.ivdnt.galahad import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext import org.apache.logging.log4j.kotlin.Logging import java.io.* import java.nio.ByteBuffer @@ -60,21 +63,8 @@ open class FileBackedValue( // It was not set yet return initValue } - - val channel = FileChannel.open(file.toPath(), StandardOpenOption.READ) - channel.use { - val lock = lockFile( channel, false ) - lock.use { - val fileSize = channel.size().toInt() - val byteBuffer: ByteBuffer = ByteBuffer.allocate(fileSize) - channel.read(byteBuffer) - byteBuffer.flip() - val bytes: ByteArray = byteBuffer.array() - byteBuffer.clear() - return mapper.readValue( bytes, object : TypeReference() {}) - } - } - + val bytes: ByteArray = runBlocking(Dispatchers.IO) { file.inputStream().use { it.readBytes() }} + return mapper.readValue(bytes, object : TypeReference() {}) } /** @@ -88,41 +78,10 @@ open class FileBackedValue( if( !file.exists() ) { file.createNewFile() } - // Would love to do this atomically, but for now we won't val oldValue = read() - - val channel = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING ) - channel.use { - val lock = lockFile( channel, true ) - lock.use { - val newValue = modification( oldValue ) - val newValBytes = mapper.writeValueAsBytes( newValue ) - logger.trace("will write $newValue") - val byteBuffer = ByteBuffer.wrap( newValBytes ) - channel.write( byteBuffer ) - } - } + val newValue = modification(oldValue) + val newValBytes = mapper.writeValueAsBytes(newValue) + runBlocking(Dispatchers.IO) { file.writeBytes(newValBytes)} } - - fun lockFile( channel: FileChannel, exclusive: Boolean ): FileLock? { - while (true) { - try { - return if( exclusive ) { - channel.lock() - } else { - channel.lock(0L, Long.MAX_VALUE, true) - } - } catch (ignored: OverlappingFileLockException) { - } catch (ignored: IOException) { - } - try { - logger.info("Tried to read access $file but it was locked. Will sleep for ${LOCK_SLEEP_TIME}ms now then retry.") - Thread.sleep(LOCK_SLEEP_TIME) - } catch (e: InterruptedException) { - e.printStackTrace() - } - } - } - } \ No newline at end of file