0

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

1 Answers1

3

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.

Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
  • But how about I change line in else- def take(): Future[Int] = { val processResponseF: Future[Boolean] = performSomeAction() processResponseF.flatMap( processResponse => { if(processResponse) Future.successful(100) else Future.successful(10) + take() //changed line } ) } Now will it need to keep stack of old calls? – user3635344 Mar 14 '17 at 04:25
  • @user3635344 Then it doesn't compile, because you cannot write `Future(10) + take()`. You can't add futures without mapping. – Michael Zajac Mar 14 '17 at 04:28
  • Hmm. Right. It will be needed to write in future block. Thank you very much. :) – user3635344 Mar 14 '17 at 04:35