In Scala, if I know that a piece of code is running in a Future, is there a way of finding out in which ExecutionContext the Future resides? Eg, so that I can write out this information to a log.
Don't worry, I don't want to do anything nefarious. I just want the information for debugging.
Viktor Klang had this to say in a comment:
Any sensible ExecutionContext ought to name its threads appropriately, then it shows up in logs using Thread.currentThread().getName().
I think that this is just what I need.
Thanks, Viktor!
Not clear what do you want, but if you want to get the implicit
variable in Future
context, you can do it like:
def main(args: Array[String]): Unit = {
helloWorld()
fooBar()
}
def fooBar(): Unit = {
import scala.concurrent.ExecutionContext.Implicits.global
Future {
println(implicitly[ExecutionContext].hashCode())
"foo bar"
}
}
def helloWorld(): Unit = {
implicit val ec = ExecutionContext.fromExecutor(Executors.newFixedThreadPool(10))
Future {
println(implicitly[ExecutionContext].hashCode())
"Hello World"
}
}
use implicitly with the implicit
type to get the implicit
variable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.