From c64ae4e33932aad10b22956352493e310f020521 Mon Sep 17 00:00:00 2001 From: carbotaniuman <41451839+carbotaniuman@users.noreply.github.com> Date: Tue, 11 Aug 2020 14:42:00 -0500 Subject: [PATCH] Third try at concurrency --- src/main/kotlin/mdnet/base/MangaDexClient.kt | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/main/kotlin/mdnet/base/MangaDexClient.kt b/src/main/kotlin/mdnet/base/MangaDexClient.kt index b19d6bc..5566a79 100644 --- a/src/main/kotlin/mdnet/base/MangaDexClient.kt +++ b/src/main/kotlin/mdnet/base/MangaDexClient.kt @@ -28,7 +28,9 @@ import com.fasterxml.jackson.module.kotlin.readValue import java.io.File import java.io.FileReader import java.io.IOException +import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors +import java.util.concurrent.ScheduledFuture import java.util.concurrent.TimeUnit import java.util.regex.Pattern import mdnet.base.Main.dieWithError @@ -46,6 +48,7 @@ class ClientSettingsException(message: String) : Exception(message) class MangaDexClient(private val settingsFile: File, databaseFile: File, cacheFolder: File) { // this must remain single-threaded because of how the state mechanism works private val executor = Executors.newSingleThreadScheduledExecutor() + private lateinit var scheduledFuture: ScheduledFuture<*> private val database: Database private val cache: DiskLruCache @@ -89,7 +92,7 @@ class MangaDexClient(private val settingsFile: File, databaseFile: File, cacheFo fun runLoop() { LOGGER.info { "Mangadex@Home Client initialized - starting normal operation." } - executor.scheduleWithFixedDelay({ + scheduledFuture = executor.scheduleWithFixedDelay({ try { // this blocks the executor, so no worries about concurrency reloadClientSettings() @@ -145,22 +148,31 @@ class MangaDexClient(private val settingsFile: File, databaseFile: File, cacheFo } fun shutdown() { + LOGGER.info { "Mangadex@Home Client shutting down" } + val latch = CountDownLatch(1) + + scheduledFuture.cancel(false) + executor.schedule({ - LOGGER.info { "Mangadex@Home Client shutting down" } if (webUi != null) { stopWebUi() } if (imageServer != null) { stopImageServer() } - LOGGER.info { "Mangadex@Home Client has shut down" } try { cache.close() } catch (e: IOException) { LOGGER.error(e) { "Cache failed to close" } } + + latch.countDown() }, 0, TimeUnit.SECONDS) + + latch.await() + executor.shutdown() + LOGGER.info { "Mangadex@Home Client has shut down" } } /**