Scala Future [T] is locked inside? What's going on inside Scala Future?

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

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

      

Code in the future above the blocks.

My question is , since it Future

uses ExecutionContext

. Does this mean that some thread in this thread pool will be blocked by this future while executing code inside it?

Which thread will exactly call the callback? Another thread from the thread pool? How does he know that the code executed in this future is complete?

+3


source to share


1 answer


Assuming you are calling code that blocks in Future

:

as Future uses ExecutionContext

. Does this mean that some thread in this thread pool will be blocked by this future while executing code inside it?

Essentially, yes. If you are calling blocking code, something needs to be blocked. However, it ExecutionContext

is more general than a thread pool. It could be a thread pool, but it could also just be something that handles calls in some other way. However, something will be blocked, most often it will be a thread. scala.concurrent.ExecutionContext.Implicits.global

- this ForkJoinPool

, for example.

Which thread will exactly call the callback?



It mostly depends on ExecutionContext

. You can print Thread.currentThread

in the callback code, but there is no reason (other than debugging) why you really need to know this information. Of course, your code doesn't need to know. This usually means the next available thread in the pool, which can be the same thread that executed the body Future

, or a different one. It looks like the same thread that is executing the original Future

will send callbacks, but this only schedules them for execution.

How does he know that the execution of the code in this future is complete?

The call onComplete

will be executed immediately if the underlying Promise

one Future

is in a completed state, or it CallbackRunnable

will be added to the list of listeners to be executed when the promise is complete. DefaultPromise#tryComplete

will call listeners right after the computation is done. See this snippet of current code.

+2


source







All Articles