Created
October 13, 2016 03:48
-
-
Save pfgray/ec62fd518d8238f42534b77c70cafe83 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
| import java.util.function.Supplier | |
| import scalaj.http.Http | |
| import scala.concurrent.blocking | |
| import scala.concurrent.Future | |
| import scala.concurrent.ExecutionContext.Implicits.global | |
| import scalaz.concurrent.Task | |
| object AsyncTest { | |
| def main(args: Array[String]): Unit = { | |
| val start = System.currentTimeMillis() | |
| println(s"We have: ${Runtime.getRuntime.availableProcessors()} available processors") | |
| val arr = for (_ <- 1 to 5) yield thingTask() | |
| val sum = Task.gatherUnordered(arr) unsafePerformSync | |
| val end = System.currentTimeMillis() | |
| println(s"got ${sum}, in ${(end - start) / 1000} s") | |
| // prints out: | |
| // We have: 4 available processors | |
| // thread: pool-1-thread-3 was used: 0 times | |
| // thread: pool-1-thread-4 was used: 0 times | |
| // thread: pool-1-thread-1 was used: 0 times | |
| // thread: pool-1-thread-2 was used: 0 times | |
| // thread: pool-1-thread-2 was used: 1 times | |
| // got List((), (), (), (), ()), in 2 s | |
| } | |
| def thingTask() = { | |
| Task { | |
| println(s"thread: ${Thread.currentThread().getName} was used: ${ThreadLocalInvokeCount.get()} times") | |
| Thread.sleep(1000) | |
| } | |
| } | |
| def requestHttp(): Future[String] = | |
| Future { | |
| blocking { | |
| //println(s"thread: ${Thread.currentThread().getName} was used: ${ThreadInvokeCount.get()} times") | |
| val resp = Http("http://localhost:3000/delay").asString.body | |
| resp | |
| } | |
| } | |
| def thing() = { | |
| Future { | |
| println("okay, sleeping...") | |
| // now let's replace Thread.sleep, with an http request | |
| blocking { | |
| Thread.sleep(1000) | |
| println(s"after in thread: ${Thread.currentThread().getName}") | |
| } | |
| 5 | |
| } | |
| } | |
| } | |
| object ThreadLocalInvokeCount { | |
| val count = ThreadLocal.withInitial(new Supplier[Int] { | |
| override def get(): Int = 0 | |
| }) | |
| def get(): Int = { | |
| val orig = count.get() | |
| count.set(1 + orig) | |
| orig | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment