[英]Why does MongoDB observeOn not use the specified execution context?
在Scala中,我编写了两个MongoDB可观察对象,并在传递自定义执行上下文时调用了observeOn。 对observeOn的调用是在第一个可观察对象上进行的,但是自定义执行上下文不会传播到第二个可观察对象。
为了说明这一点,我编写了下面的独立代码:
import java.util.concurrent.{LinkedBlockingQueue, ThreadPoolExecutor, TimeUnit}
import org.apache.commons.lang3.concurrent.BasicThreadFactory.Builder
import org.mongodb.scala.bson.collection.immutable.Document
import org.mongodb.scala.{MongoClient, Observable}
import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext}
object Test extends App {
val client = MongoClient("mongodb://localhost")
def insertObs = {
client.getDatabase("test").getCollection("test").insertOne(Document("test" -> 1))
}
val threadPool = new ThreadPoolExecutor(2, 2, 0L,
TimeUnit.MILLISECONDS, new LinkedBlockingQueue[Runnable],
new Builder().namingPattern("Custom pool").build())
val executionContext = ExecutionContext fromExecutor (threadPool)
val obs = Observable(List(1, 2, 3))
val res =
obs.observeOn(executionContext).map {
i =>
println("OBS " + Thread.currentThread().getName)
i
}.flatMap(_ => insertObs.map {
i =>
println("INSERT " + Thread.currentThread().getName)
i
})
Await.result(res.toFuture(), Duration(20, TimeUnit.SECONDS))
}
其输出如下:
OBS Custom pool
INSERT Thread-2
OBS Custom pool
INSERT Thread-2
OBS Custom pool
INSERT Thread-4
我期望在执行“ INSERT”可观察对象时,仅将“自定义池”用作执行上下文,而不是将Thread-2和Thread-4用作执行上下文。 如此处文档所述:
具体来说,它表示:将特定的执行上下文用于将来的操作
为什么自定义线程池不用于“插入”可观察对象?
这似乎按预期工作:请参阅此票证: https : //jira.mongodb.org/browse/SCALA-437
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.