Skip to content

Instantly share code, notes, and snippets.

@Anamorphosee
Last active February 12, 2024 07:22
Show Gist options
  • Save Anamorphosee/9a6436b9093b597ea69be405443f33ad to your computer and use it in GitHub Desktop.
Save Anamorphosee/9a6436b9093b597ea69be405443f33ad to your computer and use it in GitHub Desktop.
loom ui example
@file:Suppress("JAVA_MODULE_DOES_NOT_EXPORT_PACKAGE")
import jdk.internal.vm.Continuation
import jdk.internal.vm.ContinuationScope
import javax.swing.SwingUtilities
class UILoomScope(
private val continuationScope: ContinuationScope,
private val continuation: Continuation
) {
fun yield(actionNotInUIThread: () -> Unit = { }) {
Thread.ofVirtual().name("NotUI").start() {
actionNotInUIThread()
SwingUtilities.invokeLater {
continuation.run()
}
}
Continuation.yield(continuationScope)
}
}
class UILoomAction(private val action: UILoomScope.() -> Unit) {
private val continuationScope = ContinuationScope("loom action")
private val continuation = Continuation(continuationScope) {
runAction()
}
private val scope = UILoomScope(continuationScope, continuation)
fun run() {
SwingUtilities.invokeLater {
continuation.run()
}
}
private fun runAction() {
scope.action()
}
}
fun main() {
val action = UILoomAction() {
println("Action 1 in Thread: ${Thread.currentThread().name}")
yield {
println("Not UI action in Thread: ${Thread.currentThread().name}")
}
println("Action 2 in Thread: ${Thread.currentThread().name}")
}
action.run()
}
@Anamorphosee
Copy link
Author

Anamorphosee commented Jan 27, 2023

Run with --enable-preview --add-exports java.base/jdk.internal.vm=ALL-UNNAMED JVM arguments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment