u/myousuf65

▲ 4 r/Kotlin

Help Required with running parallel coroutines for Fille IO

        <dependency>
            <groupId>org.jetbrains.kotlinx</groupId>
            <artifactId>kotlinx-coroutines-core</artifactId>
            <version>1.11.0</version>
        </dependency>
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import kotlin.time.Duration.Companion.milliseconds


suspend fun createFile(idx: Int) {
    val filename = "/Users/myousuf/dev/test/testfiles/file$idx.txt"
    val file = File(filename)
    withContext(Dispatchers.IO) {
        file.createNewFile()
    }
    file.writeText("hello world how are you my name is test")
}

suspend fun deleteFile(idx: Int) {
    val filename = "/Users/myousuf/dev/test/testfiles/file$idx.txt"
    val file = File(filename)
    withContext(Dispatchers.IO){
        file.delete()
    }
}

suspend fun main() {

    val startDelete = System.currentTimeMillis()
    println("starting delete operation now")
    coroutineScope {
        List(300_000) { idx ->
            launch(Dispatchers.IO) {
                deleteFile(idx)
            }
        }
    }
    val endDelete = System.currentTimeMillis();
    val diffDelete = endDelete - startDelete
    println("Delete operation took: ${diffDelete.milliseconds.inWholeSeconds} seconds")


    val dir = File("/Users/myousuf/dev/test/testfiles")
    println(dir.listFiles()?.forEach { println(it.name)})

    println("starting file creation now")
    val starttime = System.currentTimeMillis()
    coroutineScope {
        List(300_000) { idx ->
            launch(Dispatchers.IO) {
                createFile(idx)
            }
        }
    }
    val endtime = System.currentTimeMillis()
    val diff = endtime - starttime
    println("time taken for file creation: ${diff.milliseconds.inWholeSeconds} seconds")

}

So this is my code, and the following is the output of this code.

starting delete operation now
Delete operation took: 15 seconds
kotlin.Unit
starting file creation now
time taken for file creation: 18 seconds

Can anyone explain to me why it's taking 15 seconds? I mean, why can it not fire all these 300_000 lightweight coroutines at the same time, which will perform the create and delete operations in parallel so that everything is completed in like five seconds?

reddit.com
u/myousuf65 — 5 days ago