Ady
Ady

Reputation: 278

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.

Upvotes: 3

Views: 1454

Answers (1)

Emmanuel
Emmanuel

Reputation: 13223

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.

Upvotes: 3

Related Questions