Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coroutines limits?

I have some questions about Coroutines: Can I launch a large numbers of Coroutines, with heavy work, in parallel?

For example, I have a list of objects, and for each object I want to do some heavy work.

  • Can I do a for loop and launch a Coroutine for each object in one time?
  • How Coroutine can handle a large number of works in parallel?
  • If memory is too low, Coroutine will wait before launching another Coroutine?
  • It is better to limit Coroutines with a newFixedThreadPoolContext for example ?
like image 332
Ady Avatar asked Mar 23 '26 06:03

Ady


1 Answers

Can I launch a large numbers of Coroutines, with heavy work, in parallel?

Yes, you can. Coroutines are really lightweight. In fact a lot of coroutine examples show you can launch thousands of coroutines at a time.

Can I do a For loop and launch a Coroutine for each object in one time ?

Yes, you can. Although I do not know how efficient that would be.

How Coroutine can handle a large number of work in parallel ?

Coroutines have the notion of Dispatchers which allow you to configure threading.

If memory is too low, Coroutine will waits before launch another Coroutine ?

Coroutines behave like lightweight Threads, so memory management is up to you. I am not aware of a built in mechanism that would prevent a coroutine from being launched if the system does not have enough memory. Again, coroutines are lightweight so if you cannot launch a coroutine, there is probably something wrong going on.

It is better to limit Coroutines with a newFixedThreadPoolContext for example ?

By using newFixedThreadPoolContext, you are not really limiting the number of coroutines you can launch. You are just enforcing a limit on the ThreadPool that will be created to launch the coroutine. Also from the newFixedThreadPoolContext docs note that it will be replaced in the future.

like image 116
Emmanuel Avatar answered Mar 25 '26 20:03

Emmanuel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!