Home > Enterprise >  testing the diff between coroutin and thread, I can't get the OOM error when using thread in ko
testing the diff between coroutin and thread, I can't get the OOM error when using thread in ko

Time:07-14

I'm studying coroutine now, and testing some difference with thread. stydying with the kotlin docs, I copied some test code and changed the code for testing thread.

the docs said https://kotlinlang.org/docs/coroutines-basics.html#coroutines-are-light-weight

If you write the same program using threads (remove runBlocking, replace launch with thread, and replace delay with Thread.sleep), it will likely consume too much memory and throw an out-of-memory error.

but I can't get anything about the error. Is there any problem in my code?

fun main() = runBlocking {
    repeat(1000000) {
        thread {
            sleep(5000L)
            print(".")
        }
    }
}

CodePudding user response:

The main point in the docs is that coroutines are more light-weight than threads. But whether an out-of-memory error is thrown or not depends on the resources of your JVM. There may be enough memory to start all the 100k threads.

You can try to increase the number of threads until you get an OOM error and then try to launch the same number of coroutines, and that should work. It's easy to reproduce in the kotlin playground as it has limited resources. I've tested this piece of code there and it throws an OOM for threads but doesn't for coroutines .

import java.lang.Thread.sleep
import kotlin.concurrent.thread
import kotlinx.coroutines.*

fun main() {
    try {
        repeat(10_000) { // launch a lot of threads
            thread {
                sleep(5000L)
                print(".")
            }
        }
    } catch (e: java.lang.OutOfMemoryError) {
        println("Thread creation failed: "   e)
    }
    try {
        runBlocking {
            repeat(10_000) { // launch a lot of coroutines
                launch {
                    delay(5000L)
                    print(".")
                }
            }
        }
    } catch (e: java.lang.OutOfMemoryError) {
        println("Coroutine creation failed: "   e)
    }
}

CodePudding user response:

Your quote also said to remove the runBlocking. The following code did only timeout on my machine, limited to 30s.

fun main() = repeat(1000000) {
    thread {
        Thread.sleep(5000L)
        print(".")
    }
}
main()
  • Related