3

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? E.g., 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.

Douglas
  • 2,555
  • 3
  • 24
  • 30

2 Answers2

3

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!

Douglas
  • 2,555
  • 3
  • 24
  • 30
2

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.

Community
  • 1
  • 1
chengpohi
  • 14,064
  • 1
  • 24
  • 42
  • Thanks for your help. That's useful information. Unfortunately, it won't work for me. Your solution will only work within the body of the "Future" constructor. Where I want to do the logging is within in a function that is being run by a thread that was created by a "Future" constructor, but by the time we are within the body of the function in question, the construction of the the future is long gone. (Perhaps I can just log a stack trace and that will have enough information? But that seems a bit noisy and heavy-handed.) – Douglas Jul 22 '16 at 13:24