Last active
February 26, 2021 15:13
-
-
Save kostapc/aef540c3170b29d81e0a05231b42d85d to your computer and use it in GitHub Desktop.
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
import kotlinx.coroutines.sync.Semaphore | |
import java.util.concurrent.Executors | |
import java.util.concurrent.atomic.AtomicReference | |
object AsyncIoThread { | |
private val executor = Executors.newCachedThreadPool { run -> | |
val thread = Thread(run) | |
thread.name = "AsyncIoThread-${thread.name}" | |
thread.isDaemon = true | |
thread | |
} | |
/** | |
* Coroutine will be suspended, | |
* but code will be executed on separate thread and coroutine scope stays not thread-blocking. | |
*/ | |
suspend fun <A> runIsolatedSync( | |
code: () -> A | |
): A? { | |
val res = AtomicReference<A?>(null) | |
val semaphore = Semaphore(1, 1) | |
executor.submit { | |
res.set(code()) | |
semaphore.release() | |
} | |
semaphore.acquire() | |
return res.get() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment