From 0b3aac618933aae1c12c345413fe2fb0df804928 Mon Sep 17 00:00:00 2001 From: DBotThePony Date: Wed, 22 May 2024 18:59:57 +0700 Subject: [PATCH] Game loading now no longer blocks universe thread and it can perform other work --- .../ru/dbotthepony/kstarbound/Starbound.kt | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/main/kotlin/ru/dbotthepony/kstarbound/Starbound.kt b/src/main/kotlin/ru/dbotthepony/kstarbound/Starbound.kt index bfc3050b..8d06f39f 100644 --- a/src/main/kotlin/ru/dbotthepony/kstarbound/Starbound.kt +++ b/src/main/kotlin/ru/dbotthepony/kstarbound/Starbound.kt @@ -13,8 +13,10 @@ import kotlinx.coroutines.Runnable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.async +import kotlinx.coroutines.delay import kotlinx.coroutines.future.asCompletableFuture import kotlinx.coroutines.future.await +import kotlinx.coroutines.launch import org.apache.logging.log4j.LogManager import org.classdump.luna.compiler.CompilerChunkLoader import org.classdump.luna.compiler.CompilerSettings @@ -344,7 +346,6 @@ object Starbound : BlockableEventLoop("Universe Thread"), Scheduler, ISBFileLoca registerTypeAdapterFactory(JsonReference.Companion) - registerTypeAdapter(ColorReplacements.Companion) registerTypeAdapterFactory(BlueprintLearnList.Companion) registerTypeAdapter(RGBAColorTypeAdapter) @@ -619,7 +620,7 @@ object Starbound : BlockableEventLoop("Universe Thread"), Scheduler, ISBFileLoca return files } - private fun doInitialize() { + private suspend fun doInitialize() { if (!initializing && !initialized) { initializing = true } else { @@ -665,21 +666,29 @@ object Starbound : BlockableEventLoop("Universe Thread"), Scheduler, ISBFileLoca loaded = toLoad - tasks.size loadingProgress = (total - tasks.size) / total loadingProgressText = "Loading JSON assets, $loaded / $toLoad" - LockSupport.parkNanos(5_000_000L) + delay(10L) } - Registries.finishLoad() - RecipeRegistry.finishLoad() ItemRegistry.finishLoad() - Registries.validate() initializing = false initialized = true + + // Suggest VM to reclaim memory after game has been loaded + System.gc() } + private var initializationFuture: CompletableFuture<*>? = null + fun initializeGame(): CompletableFuture<*> { - return submit { doInitialize() } + return supplyAsync { + if (initializationFuture == null) { + initializationFuture = scope.launch { doInitialize() }.asCompletableFuture() + } + + return@supplyAsync initializationFuture!! + }.thenCompose { it } } private var fontPath: File? = null