Skip to content

Instantly share code, notes, and snippets.

@siddharth1001
Last active May 25, 2023 07:09
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/0960afd67991bb21a0821e8fa835cef5 to your computer and use it in GitHub Desktop.
Save siddharth1001/0960afd67991bb21a0821e8fa835cef5 to your computer and use it in GitHub Desktop.
How not to write coroutines
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 {
performBlockingOperation("job1")
}
val job2 = launch {
performBlockingOperation("job2")
}
val job3 = launch {
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 : main
Blocking operation completed. jobName = job2, thread : main
Blocking operation completed. jobName = job3, thread : main
Total execution time: 3020 ms // this value(3020) may change but should be slightly greater than 3000ms.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment