Michael
Michael

Reputation: 42050

Does this code with nested Futures create a deadlock?

Suppose I've got an ExecutionContext backed a fixed thread pool and function foo, which creates two nested Futures.

import scala.concurrent._

implicit val ec = ExecutionContext.fromExecutor(new ThreadPoolExecutor(...))
def foo(): Future[Int] = new Future {
  ...
  new Future { ... }
}   

I guess this code may create a deadlock when foo creates many Futures that take all the threads and then get stuck because they cannot create the second nested Future. Is it correct ?

Upvotes: 1

Views: 253

Answers (1)

Tim
Tim

Reputation: 27356

As long as all Futures run to completion without blocking then there can be no deadlock.

If the code inside a Future is going to block it should be inside a blocking statement. This will create a new thread to prevent thread starvation of the original thread pool.

If a Future waits for the results that will be generated by another Future then there is the potential for deadlock.

Upvotes: 2

Related Questions