代码之家  ›  专栏  ›  技术社区  ›  uzaysan

春季启动的kotlin协同程序不并行运行

  •  0
  • uzaysan  · 技术社区  · 2 年前

    我正在用springboot和kotlin构建一个后端应用程序。我想实现一个特定方法的并行执行。我尝试使用协程,但底层方法是同步运行的。

    这是我迄今为止所尝试的:

    fun getXsByIds(xIds: List<String>): List<X> {
            val xList = ArrayList<X>();
            runBlocking {
                val promises = xIds.map {
                    async {
                        getXById(it)
                    }
                };
                
                xList.addAll((promises.awaitAll()).filterNotNull())
            }
            return xList;
        }
    
        fun getXById(xId: String): X? {
            // This method makes request to database
        }
    

    当我放入日志时 getXById 这样的方法

    fun getXById(xId: String): X? {
            print("start");
            // This method makes request to database
            print("end");
        }
    

    我得到这个输出

    start
    end
    start
    end
    start
    end
    ...
    

    为什么我的郊游不并行?这是弹簧靴。没有反应。按请求线程样式。

    1 回复  |  直到 2 年前
        1
  •  2
  •   Pawel    2 年前

    使命感 async 不指定任何协程元素意味着它将从其父级继承所有协程元素(作业除外)。这会导致您的“异步”调用在上执行 runBlocking s阻塞调度程序。

    尝试使用 async(Dispatchers.Default) { ... } 相反