Skip to content

Instantly share code, notes, and snippets.

@siddharth1001
Last active May 25, 2023 08:45
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 siddharth1001/523b6dfb1d02cd7f6bcce6bc01f60c1f to your computer and use it in GitHub Desktop.
Save siddharth1001/523b6dfb1d02cd7f6bcce6bc01f60c1f to your computer and use it in GitHub Desktop.
How to write coroutines efficiently - 1
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
fun performBlockingOperation(jobName: String) {
// Simulating a blocking operation
Thread.sleep(1000)
println("Blocking operation completed. jobName = $jobName, thread : ${Thread.currentThread().name}")
}
fun main() = runBlocking {
val executionTime = measureTimeMillis {
val job1 = launch {
withContext(Dispatchers.IO) {
performBlockingOperation("job1")
}
}
val job2 = launch {
withContext(Dispatchers.IO) {
performBlockingOperation("job2")
}
}
val job3 = launch {
withContext(Dispatchers.IO) {
performBlockingOperation("job3")
}
}
println("Coroutine launched")
joinAll(job1, job2, job3)
}
println("Total execution time: $executionTime ms")
}
/*
Console Output:
Coroutine launched
Blocking operation completed. jobName = job1, thread : DefaultDispatcher-worker-1
Blocking operation completed. jobName = job2, thread : DefaultDispatcher-worker-3
Blocking operation completed. jobName = job3, thread : DefaultDispatcher-worker-2
Total execution time: 1033 ms
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment