aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/DelayedRun.kt30
-rw-r--r--src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt7
2 files changed, 20 insertions, 17 deletions
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/DelayedRun.kt b/src/main/java/at/hannibal2/skyhanni/utils/DelayedRun.kt
index f90237588..284946072 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/DelayedRun.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/DelayedRun.kt
@@ -1,34 +1,30 @@
package at.hannibal2.skyhanni.utils
-import at.hannibal2.skyhanni.utils.LorenzUtils.editCopy
+import at.hannibal2.skyhanni.utils.LorenzUtils.drainTo
+import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.time.Duration
-// TODO find better sync bug fix than creating a new map for each use
object DelayedRun {
- var map = mapOf<() -> Any, SimpleTimeMark>()
+ private val tasks = mutableListOf<Pair<() -> Any, SimpleTimeMark>>()
+ private val futureTasks = ConcurrentLinkedQueue<Pair<() -> Any, SimpleTimeMark>>()
fun runDelayed(duration: Duration, run: () -> Unit) {
- map = map.editCopy {
- this[run] = SimpleTimeMark.now() + duration
- }
+ futureTasks.add(Pair(run, SimpleTimeMark.now() + duration))
}
+ /** Runs in the next full Tick so the delay is between 50ms to 100ms**/
fun runNextTick(run: () -> Unit) {
- map = map.editCopy {
- this[run] = SimpleTimeMark.now()
- }
+ futureTasks.add(Pair(run, SimpleTimeMark.farPast()))
}
fun checkRuns() {
- if (map.isEmpty()) return
- map = map.editCopy {
- entries.removeIf { (runnable, time) ->
- val inPast = time.isInPast()
- if (inPast) {
- runnable()
- }
- inPast
+ tasks.removeIf { (runnable, time) ->
+ val inPast = time.isInPast()
+ if (inPast) {
+ runnable()
}
+ inPast
}
+ futureTasks.drainTo(tasks)
}
}
diff --git a/src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt b/src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt
index 666ea54ea..8371c9176 100644
--- a/src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt
+++ b/src/main/java/at/hannibal2/skyhanni/utils/LorenzUtils.kt
@@ -43,6 +43,7 @@ import java.util.Timer
import java.util.TimerTask
import java.util.WeakHashMap
import java.util.regex.Matcher
+import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KMutableProperty1
import kotlin.reflect.KProperty
@@ -701,8 +702,14 @@ object LorenzUtils {
return runCatching { this.group(groupName) }.getOrNull()
}
+ fun <E> ConcurrentLinkedQueue<E>.drainTo(list: MutableCollection<E>) {
+ while (true)
+ list.add(this.poll() ?: break)
+ }
+
// Let garbage collector handle the removal of entries in this list
fun <T> weakReferenceList(): MutableSet<T> = Collections.newSetFromMap(WeakHashMap<T, Boolean>())
fun <T> MutableCollection<T>.filterToMutable(predicate: (T) -> Boolean) = filterTo(mutableListOf(), predicate)
+
}