Created
August 14, 2020 02:31
-
-
Save oshiro-kazuma/6e7dad30073c6181d06c02cf4888cef2 to your computer and use it in GitHub Desktop.
execution context
This file contains 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 ExecutorSandbox.threadpool | |
import scala.concurrent._ | |
import scala.concurrent.duration.Duration | |
/** | |
* 実行方法: scalac ExecutorSandbox.scala && scala ExecutorSandbox | |
*/ | |
object ExecutorSandbox { | |
// val forkjoin = ExecutionContext.fromExecutorService(new java.util.concurrent.ForkJoinPool(3)) | |
val threadpool = ExecutionContext.fromExecutor(java.util.concurrent.Executors.newFixedThreadPool(10)) | |
val default = scala.concurrent.ExecutionContext.Implicits.global | |
def main(args: Array[String]): Unit = { | |
implicit val ec = default | |
val f = Future.sequence( | |
for (i <- 1 to 20) yield taskMix(i) | |
) | |
// すぐに表示される | |
Future(println("default ec println"))(default) | |
// ftaskMix(i) で積まれた処理が終わってから実行される | |
Future(println("threadpool ec println"))(threadpool) | |
wait(f) | |
println("finish") | |
// val f2 = Future.sequence( | |
// for (i <- 1 to 200) yield taskWithBlocking(i) | |
// for (i <- 1 to 20) yield task(i) | |
// ) | |
// run(f2) | |
// | |
// println("finish") | |
// | |
// val f = Future.sequence( | |
// for (i <- 1 to 20) yield task(i) | |
// ) | |
// run(f) | |
} | |
def wait(f: Future[_])(implicit ec: ExecutionContext): Unit = Await.ready(f, Duration.Inf) | |
def taskWithBlocking(i: Int)(implicit ec: ExecutionContext): Future[Unit] = { | |
Future { | |
println(s"Start $i") | |
blocking { | |
Thread.sleep(1000) | |
} | |
println(s"End $i") | |
}(ec) | |
} | |
def task(i: Int)(implicit ec: ExecutionContext): Future[Unit] = { | |
Future { | |
println(s"Start $i") | |
Thread.sleep(1000) | |
println(s"End $i") | |
}(ec) | |
} | |
def taskMix(i: Int): Future[Unit] = { | |
implicit val ec = default | |
for { | |
_ <- { | |
implicit val ec = threadpool | |
Future { | |
println(s"thread sleep $i") | |
Thread.sleep(1000) | |
} | |
} | |
_ <- { | |
implicit val ec = threadpool | |
Future { | |
println(s"non sleep $i") | |
} | |
} | |
} yield () | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment