Skip to content

Instantly share code, notes, and snippets.

@megri
Created February 18, 2015 17:27
Show Gist options
  • Save megri/3bc5952f812918332a8b to your computer and use it in GitHub Desktop.
Save megri/3bc5952f812918332a8b to your computer and use it in GitHub Desktop.
import java.util.concurrent.atomic.AtomicInteger
import scala.concurrent._
import duration._
import ExecutionContext.Implicits.global
def ftraverse[A, B](xs: Seq[A])(f: A => Future[B]): Future[Seq[B]] = {
if(xs.isEmpty) Future successful Seq.empty[B]
else f(xs.head) flatMap { fh => ftraverse(xs.tail)(f) map (r => fh +: r) }
}
def testStd(): Future[Unit] = {
val x = new AtomicInteger()
val items = 1 to 10000
Future.traverse(items)(_ => Future(x.incrementAndGet()))
Future(println(s"When I'm running x == ${x.get}"))
}
def testOp(): Future[Unit] = {
val x = new AtomicInteger()
val items = 1 to 10000
ftraverse(items)(_ => Future(x.incrementAndGet()))
Future(println(s"When I'm running x == ${x.get}"))
}
Await.result(testOp(), 2.seconds)
Await.result(testStd(), 2.seconds)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment