简体   繁体   English

Kotlin协程:并发执行限制

[英]Kotlin coroutines: concurrent execution throttling

Imagine we are reading messages from a message queue and on receive pushing them for processing into a threadpool. 想象一下,我们正在从消息队列中读取消息,并在接收时将它们推送到线程池中进行处理。 There are limited number of threads, so if all the threads are busy, we'll have natural backpressure. 线程数量有限,因此如果所有线程都忙,我们将有自然的背压。

How this can be solved in Kotlin coroutine world? 如何在Kotlin协同世界中解决这个问题? If we'll create a coroutine for each incoming message, we can very fast end up with Out of memory errors (eg if each task requires to load some data from DB) and other issues. 如果我们为每个传入的消息创建一个协同程序,我们可以非常快地结束内存不足错误(例如,如果每个任务需要从DB加载一些数据)和其他问题。

Are there any mechanisms or patterns to solve this problem? 是否有任何机制或模式可以解决这个问题?

One way to solve the issue, is to create a Channel and send your data onto it. 解决问题的一种方法是创建Channel send数据sendChannel Other threads can put a consumeEach on the channel to receive data from it. 其他线程可以在通道上放置一个consumeEach来从中接收数据。 The channel's capacity can be tweaked to your threading needs. 通道的容量可以根据您的线程需求进行调整。

Fan-out and Fan-in examples in the coroutines docs can be helpful too. 协程文档中的扇出和扇入示例也很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM