Reputation: 42100
Suppose I want to know how many threads there are in a given ExecutionContext
.
So I am writing a function like this
def count(implicit ec: ExecutionContext): Int = {
val promise = Promise[Unit]
val counter = new AtomicInteger(0)
for (_ <- 0 to 1000) Future {
counter.getAndIncrement()
Await.ready(promise.future, Duration.Inf)
}
val result = counter.get()
promise.success(())
result
}
It does not work for ExecutionContext.global
at least so I changed the implementation:
def count(implicit ec: ExecutionContext): Int = {
val barrier = new CyclicBarrier(1000)
var isReset = false
for (_ <- 0 to 1000) Future { if (!isReset) barrier.await() }
val result = barrier.getNumberWaiting
barrier.reset()
// make all futures complete and release all threads to allow JVM to exit
isReset = true
result
}
It works but I wonder
isReset
) ;ExecutionContext
is.Upvotes: 2
Views: 1335
Reputation: 48420
Try casting to particular executor, for example
implicit val ec = scala.concurrent.ExecutionContext.Implicits.global
Future(42)
ec.asInstanceOf[java.util.concurrent.ForkJoinPool].getPoolSize // : Int = 1
Upvotes: 2