0

Suppose I am writing a function to send a few concurrent HTTP GET requests and wait for all the responses with a time-out. If at least one response does not have status 200 or does not come within the time-out my function should return failure.

I am writing this function tryGets like this:

import java.net.URL

import scala.concurrent.duration._
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.util.Try

def unsafeGet(url: URL): String = {
  val in = url.openStream()
  scala.io.Source.fromInputStream(in).mkString
}

def futureGet(url: URL)
             (implicit ec: ExecutionContext): Future[String] = Future {
  unsafeGet(url)
}

def tryGets(urls: Seq[URL], timeOut: Duration)
            (implicit ec: ExecutionContext): Try[Seq[String]] = Try {
  val fut = Future.sequence(urls.map(futureGet))
  Await.result(fut, timeOut)
}

Does it make sense ? Does not it leak future instances in case of time-out ?

5
  • did you look into for comprehensions? Here is a good article about how to use it: danielwestheide.com/blog/2013/01/09/…
    – F. Lins
    Dec 20, 2017 at 18:35
  • for-comprehension executes futures sequentially rather than concurrently.
    – Michael
    Dec 21, 2017 at 4:59
  • Not if you declare them ahead of time. So you can do val x = Future{}; for{result <- x} Instead of for{result <- Future{}}
    – F. Lins
    Dec 21, 2017 at 18:37
  • here is a good explanation: alvinalexander.com/scala/…
    – F. Lins
    Dec 21, 2017 at 18:39
  • Thanks. I got it. Once I instantiate futures before for-comprehension they run concurrently.
    – Michael
    Dec 22, 2017 at 9:48

1 Answer 1

1

If one of the Future's time out, then the rest of the Future's will continue to execute because the future's are eager and will continue to run on the Execution Context. What you could do is fold over the Urls but this will execute them in serial.

urls.foldleft(Future.sucessful(Seq.empty)) { (future, url) =>
  future.flatMap(accum => futureGet(url).map(accum :+ _))
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.