Scala Concurrent Downloader example using Future

I spent this weekend learning more about Scala Futures, and believe me, posts below are the best written introductory posts about scala futures and promises.

In order to learn it for real, I started with an exercise of building a concurrent URL downloader. Basically idea is, let say, given n urls, how do you download n urls concurrently.

import //We are using WebService Client from Play's framework
import scala.concurrent._
import java.util.concurrent.Executors
import scala.util.{Success, Failure, Try}

object ConcurrentDownloader {

    def main(args: Array[String]): Unit = {

   //Future need an execution context for running them
      val executorService = Executors.newFixedThreadPool(1)
      implicit val executionContext = ExecutionContext.
      //lets define set of URLs to be downloaded
      val urls = List("",
                      "", //invalid url-1
                      "") //invalid url-2

     //Here is how we create the future for each URLs
     //execution context will run start fetching the URLs in the background
      val futures = { url => WS.url(url).get() }

    //This is a nice little trick to ensure convert a future of T to future of
      def futureToFutureTry[T](f: Future[T]): Future[Try[T]] =
     { case x => Failure(x) }

      val futureListOfTrys =

     //This is way to combine all those future into a single future
      val fseq = Future.sequence(futureListOfTrys)

      fseq onComplete {
          case Success(l) => {
              var sCount: Int = 0
              var fCount: Int = 0
              l.foreach {
                      case Success(resp) => {
                          sCount += 1 
                      case Failure(t) => {
                          fCount += 1
                          println(s"failure $t")
              println(s"success=$sCount, failures=$fCount")
          case Failure(ex) => {

There you go, you have a nice little concurrent URL downloader. I am so glad to write a concurrent program without involving any threads, locks, shared data structures, feels so refreshing!

comments powered by Disqus