Last active
May 25, 2023 07:09
-
-
Save siddharth1001/0960afd67991bb21a0821e8fa835cef5 to your computer and use it in GitHub Desktop.
How not to write coroutines
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.* | |
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