我正在使用 Kotlin 编写后端应用程序。
为了提高速度,我目前在服务器上依赖 RxKotlin 来执行诸如数据库调用和 API 调用等 IO 任务的并行执行。代码通常是这样的。
val singleResult1 = Single.fromCallable{
database.get(....)
}.io()
val singleResult2 = Single.fromCallable{
database.update(....)
}.io()
Single.zip(singleResult1, singleResult2){ result1: Result1, result2: Result2 ->
....
}
.flatMap{
//other RX calls
}
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.blockingGet()
然而,由于Rx仅适用于单个事件(而非多个事件),因此它会使代码变得混乱,并且只会添加大量样板代码(如果我想返回空值,它还会导致复杂性,并有时会破坏堆栈跟踪)。
我正在考虑移除Rx并改用Executors
(或线程)来实现并行。这里有任何性能问题需要考虑吗?
下面是我的思路示例:
fun <T> waitAll(tasks: List<Callable<T>>, threadCount: Int = -1): List<T> {
val threads = if (threadCount == -1) tasks.size else threadCount
val executor = Executors.newFixedThreadPool(threads)
val results = executor.invokeAll(tasks).map {
it.get()
}
executor.shutdown()
return results
}
并且可以这样使用:
waitAll(listOf(callable1, callable2))
或者使用普通线程并将它们连接起来?
threads.forEach{
it.start()
}
threads.forEach{
it.join()
}
或者为什么不使用流(streams)呢?
listOf(callable1,callable2)
.parallelStream()
.map{it.call()}
.collect(Collectors.toList())