Scala Future[T] 是否在内部阻塞? Scala Future 内部会发生什么?

Does Scala Future[T] block internally? What happens inside Scala Future?

val future = Future {
   println("hello")
   Thread.sleep(2000)
}

future.onComplete(_ => println("done"))

以上代码块。

我的问题是: 因为 Future 使用 ExecutionContext。这是否意味着这个线程池中的某些线程在执行其中的代码时会被这个 future 阻塞?

究竟哪个线程会调用回调?线程池中的另一个线程?它怎么会发现这个future里面执行的代码执行完了?

假设 您正在调用阻塞在 Future:

中的代码

since Future uses ExecutionContext. Does it mean, that some thread in this thread pool will be blocked by this future while executing the code inside it?

基本上,是的。如果您要调用阻塞代码,则必须阻塞 something。不过,ExecutionContext 比线程池更通用。它可以是线程池,但也可以只是以其他方式管理调用的东西。不过,有些东西还是会被阻塞,通常是线程。例如,scala.concurrent.ExecutionContext.Implicits.globalForkJoinPool

What thread exactly will call the callback?

这主要由 ExecutionContext 决定。您可以在回调代码中打印 Thread.currentThread,但没有理由(除了调试)您真的需要知道此信息。您的代码当然不需要知道。通常这意味着池中的下一个可用线程,它可以是执行 Future 主体的同一线程,也可以是不同的线程。看起来执行原始 Future 的同一个线程将分派回调,但只安排它们执行。

How will it find out, that the code execution inside this future is finished?

如果 Future 的基础 Promise 处于完成状态,则调用 onComplete 将立即执行,或者 CallbackRunnable 将被添加到列表中当承诺完成时要执行的侦听器。 DefaultPromise#tryComplete 将在计算执行后立即调用监听器。参见当前代码的this excerpt