Skip to content

Instantly share code, notes, and snippets.

@lorandszakacs
Last active May 17, 2019 11:30
Show Gist options
  • Save lorandszakacs/a28180aca59172cbcd5e to your computer and use it in GitHub Desktop.
Save lorandszakacs/a28180aca59172cbcd5e to your computer and use it in GitHub Desktop.
import java.util.concurrent.Executors
import org.scalatest.FlatSpec
import scala.language.postfixOps
import scala.concurrent.{Await, Future, ExecutionContext}
import scala.concurrent.duration._
/**
* Created by Lorand Szakacs, on 9/16/14.
*/
class AsyncVsSyncTest extends FlatSpec {
lazy val numberOfTopLevelComputations = 100
lazy val numberOfThreads = 10
def executionContext(n: Int) = new ExecutionContext {
val threadPool = Executors.newFixedThreadPool(n)
def execute(runnable: Runnable) {
threadPool.submit(runnable)
}
def reportFailure(t: Throwable) {}
}
lazy val timeout = 1 minute
behavior of "concurrency"
it should "run without a problem async" in {
implicit val ec = executionContext(numberOfThreads)
val initialTime = System.nanoTime()
val seqOfFutures: Seq[Future[String]] =
1 to numberOfTopLevelComputations map { v =>
Future {
Thread.sleep(10) //model some computation
val idF = Future {
Thread.sleep(20) //model some more computation
v + 1
}
idF map { id =>
id.toString
}
} flatMap identity
}
val futureOfList = Future.sequence(seqOfFutures)
Await.result(futureOfList, timeout)
val finishTime = System.nanoTime()
println(s"asynchronous: ${(finishTime - initialTime).toDouble / 1000000000 }")
}
it should "run with sync computation iff the numberOfThreads is greater than the the numberOfTopLevelComputations" in {
implicit val ec = executionContext(numberOfTopLevelComputations + 1)
val initialTime = System.nanoTime()
val seqOfFutures: Seq[Future[String]] =
1 to numberOfTopLevelComputations map { v =>
Future {
Thread.sleep(10) //model computation
val idF = Future {
Thread.sleep(20) //model some more computation
v + 1
}
val id = Await.result(idF, timeout)
id.toString
}
}
val futureOfList = Future.sequence(seqOfFutures)
Await.result(futureOfList, timeout)
val finishTime = System.nanoTime()
println(s"sync: ${(finishTime - initialTime).toDouble / 1000000000 }")
}
it should "timeout with sync computation if the numberOfThreads is smaller than the numberOfTopLevelComputations" in {
implicit val ec = executionContext(numberOfThreads)
val initialTime = System.nanoTime()
val seqOfFutures: Seq[Future[String]] =
1 to numberOfTopLevelComputations map { v =>
Future {
Thread.sleep(10) //model computation
val idF = Future {
Thread.sleep(20) //model some more computation
v + 1
}
val id = Await.result(idF, timeout)
id.toString
}
}
val futureOfList = Future.sequence(seqOfFutures)
Await.result(futureOfList, timeout)
val finishTime = System.nanoTime()
println(s"sync: ${(finishTime - initialTime).toDouble / 1000000000 }")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment