Last active
October 22, 2016 20:22
-
-
Save rubenpieters/b3dcd9417576c926819a4f6a2fa780bc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BlockOp(implicit ec: ExecutionContext) { | |
def blockOp(number: Int) = Future { | |
Thread.sleep(2000) | |
println(s"$number after sleep, time is now ${System.currentTimeMillis() / 1000}") | |
number | |
} | |
} | |
sealed trait TestTraverse[A] | |
case class BlockingOp(number: Int) extends TestTraverse[Int] | |
class TestTraverseInterpreter(implicit ec: ExecutionContext) extends (TestTraverse ~> Future) { | |
override def apply[A](fa: TestTraverse[A]): Future[A] = fa match { | |
case BlockingOp(number) => new BlockOp().blockOp(number) | |
} | |
} | |
// here the traverse doesn't work in parallel | |
object FreeTraverse { | |
def main(args: Array[String]) = { | |
implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(5)) | |
val prog = (1 to 10).toList.traverse(x => Free.liftF[TestTraverse, Int](BlockingOp(x))) | |
val result = prog.foldMap(new TestTraverseInterpreter) | |
val delayedResult = Await.result(result, 30.seconds) | |
println(delayedResult) | |
} | |
} | |
// here the traverse works in parallel | |
object FutureTraverse { | |
def main(args: Array[String]) = { | |
implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(5)) | |
val result = (1 to 10).toList.traverse(new BlockOp().blockOp) | |
val delayedResult = Await.result(result, 30.seconds) | |
println(delayedResult) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment