Last active
August 29, 2015 14:24
-
-
Save mikehearn/7274375de2950e10f56f to your computer and use it in GitHub Desktop.
ThreadBox/UIThreadBox
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ThreadBox<T>(private val data: T) { | |
synchronized fun use<R>(block: (T) -> R): R = block(data) | |
synchronized fun useWith<R>(block: T.() -> R): R = data.block() | |
} | |
class UIThreadBox<T>(private val data: T) { | |
fun use(block: (T) -> Unit): Unit = if (Platform.isFxApplicationThread()) block(data) else Platform.runLater { block(data) } | |
fun useWith(block: T.() -> Unit): Unit = if (Platform.isFxApplicationThread()) data.block() else Platform.runLater { data.block() } | |
/** Does a blocking get from the UI thread - danger of deadlock if not used properly! */ | |
fun getWith<R>(block: T.() -> R): R { | |
if (Platform.isFxApplicationThread()) | |
return data.block() | |
val f = CompletableFuture<R>() | |
Platform.runLater { | |
try { | |
f.complete(data.block()) | |
} catch (e: Throwable) { | |
f.completeExceptionally(e) | |
} | |
} | |
return f.get() | |
} | |
} | |
////// EXAMPLE | |
val state = ThreadBox(object { | |
val fooMap = hashMapOf<Sha256Hash, Transaction>() | |
var someFlag = false | |
}) | |
and | |
val uiState = UIThreadBox(object { | |
val uiList = FXCollections.observableArrayList<Entry>() | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment