限制Kotlin中的协程数

限制Kotlin中的协程数,kotlin,kotlin-coroutines,Kotlin,Kotlin Coroutines,我有以下代码: val mapper = ObjectMapper() val data = FileOutputStream(File("data/data.json")) val context = newFixedThreadPoolContext(nThreads = 1) val requestSemaphore = Semaphore(1) val hitsSemaphore = Semaphore(3) for (tow

我有以下代码:

 val mapper = ObjectMapper()
    val data = FileOutputStream(File("data/data.json"))
    val context = newFixedThreadPoolContext(nThreads = 1)
    val requestSemaphore = Semaphore(1)
    val hitsSemaphore = Semaphore(3)
    for (town in ExternalData.fetchTowns("31")) {
        logger.info("Handling town " + town.code)
        val elements : Flow = ElasticSearchDataFetcher.fetchDataForTown(town.code)
        val jobs = elements.map {
            hitsSemaphore.withPermit {
                async {

                    logger.info("Handling mutation with ID {} for town {}", it.second.id, town.code)
                    data.write((mapper.writeValueAsBytes(Converter.convert(it.second))))
                    data.write("\n".toByteArray())
                }
            }
        }.toList()
        jobs.forEach { it.await() }
它获取城镇列表(大约200个城镇),并从
ElasticSearch
中获取每个城镇的数据。所有城镇大约有42万张唱片

当我运行这个时,我的内存用完了(我只有6G)。我的想法是限制协同程序的数量,但我没有找到任何方法。我测试了的解决方案,但它们在我的情况下似乎不起作用


我如何限制创建的协同程序的数量或如何避免OOM?

可能在一次获取N个城镇,将数据保存在一个DB(房间?)中,然后获取下一个、批处理、执行相同操作等。
N
可以是从1到您认为安全的任何数字,考虑到数据的大小。另外,
convert.convert
可能正在分配内容(不知道)。另外,
.toList()
在最后列出了所有元素。。。所以,也许不这样做?如果使用流和
flatMapMerge
,您可以控制并发级别。