在执行上下文中获取在后台运行的期货数量的最佳方法是什么? [英] what is the best way to get the number of futures running in background in an execution context?
问题描述
我想从单元测试中检查未来是否已完成或取消,并且仍然没有在后台运行消耗 cpu 资源.一种方法是在我开始我的测试方法之前和之后检查期货的数量.最好的方法是什么?
I would like to check from the unit test if the future is completed or cancelled and still not running in the background consuming cpu resources. One way is to check the number of futures before and after i start my test method. whats the best way to do this?
推荐答案
你可以使用像 Thread.getAllStackTraces
到 获取线程及其状态.scala Future
也将在线程上运行.
You can use something as simple as Thread.getAllStackTraces
to get the threads and their states. scala Future
will run on thread as well.
import java.lang.management.ManagementFactory
import scala.concurrent.ExecutionContext
object ThreadUsage {
def main(args: Array[String]): Unit = {
val ex = ExecutionContext.Implicits.global
ex.execute(new Thread(() => {
println("executing timed task")
Thread.sleep(2000)
}))
// equivalent Future {}
// import scala.concurrent.Future
// Future {
// println("executing timed task")
// Thread.sleep(2000)
// } (ex)
ex.execute(new Thread(() => {
println("executing quick task")
}))
val running = Thread.getAllStackTraces.keySet()
running.forEach(a => {
val bean = ManagementFactory.getThreadMXBean
println(a.getThreadGroup + " " +
a.getName + " " +
a.getState + " " +
(bean.getCurrentThreadCpuTime / (1000 * 1000)) + "ms"
)
})
}
}
这将给出上面应用程序中产生的两个线程的状态,
which will give the state of two threads spawn in above app,
- scala-execution-context-global-12
- scala-execution-context-global-14
输出:
executing timed task
executing quick task
java.lang.ThreadGroup[name=main,maxpri=10] scala-execution-context-global-14 WAITING 528ms
java.lang.ThreadGroup[name=system,maxpri=10] Reference Handler WAITING 528ms
java.lang.ThreadGroup[name=main,maxpri=10] Monitor Ctrl-Break RUNNABLE 528ms
java.lang.ThreadGroup[name=main,maxpri=10] main RUNNABLE 528ms
java.lang.ThreadGroup[name=main,maxpri=10] scala-execution-context-global-12 TIMED_WAITING 528ms
java.lang.ThreadGroup[name=system,maxpri=10] Signal Dispatcher RUNNABLE 528ms
java.lang.ThreadGroup[name=system,maxpri=10] Finalizer WAITING 528ms
您可以改为使用图形工具,例如 jmc
(java 任务控制) 和 jconsole
查看正在运行的线程及其 CPU 使用率等.
You can instead use graphic tool like jmc
(java mission control) and jconsole
to see the running threads with their CPU usage and all.
这篇关于在执行上下文中获取在后台运行的期货数量的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!