Skip to content

Instantly share code, notes, and snippets.

@kostapc
Last active February 26, 2021 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kostapc/aef540c3170b29d81e0a05231b42d85d to your computer and use it in GitHub Desktop.
Save kostapc/aef540c3170b29d81e0a05231b42d85d to your computer and use it in GitHub Desktop.
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