Home > Blockchain >  Scala: thread is unable to access variable outside of thread?
Scala: thread is unable to access variable outside of thread?

Time:01-02

object Test extends App {
  val x = 0
  val threadHello = (1 to 5).map(_ => new Thread(() => {
    println("Hello")
    println(x) // this results in join never resolving "collecting data"
  }))
  threadHello.foreach(_.start())
  threadHello.foreach(_.join())
  println(x)
}

I'm still learning about concurrency in Scala but I'm having an issue where thread.join() never resolves and the program ends up running forever, UNLESS I comment out the println(x) statement.

Debugging reveals that the thread is never able to access the value of x, and I'm not sure why this is an issue.

The problem highlighted when debugging in IntelliJ

CodePudding user response:

Your code actually runs just fine for me, in Scala 2.13.

That said, I suspect your problem has to do with the initialization order of vals in scala.App. If so, you should be able to work around it by making x lazy, like so:

object Test extends App {
  lazy val x = 0
  val threadHello = (1 to 5).map(_ => new Thread(() => {
    println("Hello")
    println(x) // this results in join never resolving "collecting data"
  }))
  threadHello.foreach(_.start())
  threadHello.foreach(_.join())
  println(x)
}

Alternatively, just don't use scala.App:

object Main {
  def main(args: Array[String]) {
    val x = 0
    val threadHello = (1 to 5).map(_ => new Thread(() => {
      println("Hello")
      println(x) // this results in join never resolving "collecting data"
    }))
    threadHello.foreach(_.start())
    threadHello.foreach(_.join())
    println(x)
  }
}
  • Related