Search code examples
scalarecursionstack-overflowconcurrent.futures

Scala: Recursion with future Stack overflow error


Consider below code snippet. Too many take() calls will result in stack overflow error. What is the good strategy to overcome such scenarios?

def take(): Future[Int] = {
    val processResponseF: Future[Boolean] = performSomeAction()
    processResponseF.flatMap(
      processResponse => {
        if(processResponse)
          Future.successful(100)
        else
          take()
      }
    )
  }

def performSomeAction(): Future[Boolean] = {
  //This returns future of boolean
}

Assumption - 1. Method signature should not be changed


Solution

  • Too many take() calls will result in stack overflow error.

    It won't. When a method that returns a Future recursively calls itself, all that method knows is that it has a future value that will be filled (maybe) later. The actual code is executed on a different stack, as it needs to be done asynchronously from the original call, and may not even happen on the same thread.