本文介绍了在Scala中阻塞关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
未来(blocking(blockingCall())
和阻塞(Future(blockingCall())之间有什么区别
?这两个都定义在 scala.concurrent ._
What's the difference between Future(blocking(blockingCall()))
and blocking(Future(blockingCall()))
? Both of these are defined in scala.concurrent._
我看过和其他一些。
I've explained blocking
more in depth in this answer.
REPL示例:
import java.util.concurrent.Executors
import scala.concurrent._
val ec = scala.concurrent.ExecutionContext.Implicits.global
val executorService = Executors.newFixedThreadPool(4)
val ec2 = ExecutionContext.fromExecutorService(executorService)
def blockingCall(i: Int): Unit = { Thread.sleep(1000); println("blocking call.. " + i) }
// Spawns enough new threads in `ec` to handle the 100 blocking calls
(0 to 100) foreach { i => Future(blocking(blockingCall(i)))(ec) }
// Does not spawn new threads, and `ec2` reaches thread starvation
// execution will be staggered as threads are freed
(0 to 100) foreach { i => Future(blocking(blockingCall(i)))(ec2) }
// `blocking` does nothing because the `Future` is executed in a different context,
// and `ec2` reaches thread starvation
(0 to 100) foreach { i => blocking(Future(blockingCall(i))(ec2)) }
// `blocking` still does nothing, but `ec` does not know to spawn new threads (even though it could)
// so we reach thread starvation again
(0 to 100) foreach { i => blocking(Future(blockingCall(i))(ec)) }
这篇关于在Scala中阻塞关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!