Skip to content

Instantly share code, notes, and snippets.

@fadi-botros
Created June 3, 2021 07:44
Show Gist options
  • Save fadi-botros/0922c0220efc96b7e34f10463d16e6f4 to your computer and use it in GitHub Desktop.
Save fadi-botros/0922c0220efc96b7e34f10463d16e6f4 to your computer and use it in GitHub Desktop.
A Kotlin Coroutine snippet trying to simulate what happens in Spring WebFlux
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import java.util.concurrent.Executor
import java.util.concurrent.Executors
import kotlin.coroutines.suspendCoroutine
// Simulate what may happen in Spring WebFlux, where a Spring call your functions in their executors
suspend fun resumeOnSpecificJavaExecutor(javaExecutor: Executor) = suspendCoroutine<Int> {
javaExecutor.execute { it.resumeWith(Result.success(1)) }
}
fun main() {
// Make the single thread executor that is outside the main thread, and print its thread id
val executor = Executors.newSingleThreadExecutor()
executor.execute { println("Inside the Thread Executor, Thread Id ${Thread.currentThread().id}") }
// Use the Unconfined, it would be executed on the main thread (Id = 1), then either resumed
// on the same thread, or will be resumed on the specific executor that is made in the previous step
runBlocking {
withContext(Dispatchers.Unconfined)
{
println("Coroutine, Thread Id ${Thread.currentThread().id}")
val result = resumeOnSpecificJavaExecutor(executor)
println("Coroutine, Thread Id ${Thread.currentThread().id}, Result is ${result}")
}
}
// Use IO dispatcher, which executes and resumes the coroutine on a thread pool allocated by Kotlin
runBlocking {
withContext(Dispatchers.IO)
{
println("Coroutine, Thread Id ${Thread.currentThread().id}")
val result = resumeOnSpecificJavaExecutor(executor)
println("Coroutine, Thread Id ${Thread.currentThread().id}, Result is ${result}")
}
}
executor.shutdown()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment