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
- why the first implementation does not work;
- how to improve the "barrier" implementation (e.g. get rid of the
isReset
) ; - what the best way to count threads in an
ExecutionContext
is.
Try casting to particular executor, for example