0

How is num being accessed by the new thread. Future will execute on the new thread. how is the value of num that is in the stack frame of main thread accessible in the new thread? Where is it stored?

object TestFutureActor extends App {

  var num = 10

  val addNum = Future {

    num = num + 2
    num

  }
}
Arpan Patro
  • 153
  • 2
  • 8

1 Answers1

0

It's question in generally about JVM memory model. Really you can read your variable value from different places. It can be in processor cache or in memory e.g.. Your parallel reads/writes will be non-synchronized in general. For example code below is absolutely legal for JVM.

var a, b = 0
Thread 1 | Thread 2
a = 1    | val c = b // c = 2
b = 2    | val d = a // d = 0

If you need to synchronize your actions with variable you need to use happens-before synchronization between them.

It's very deep question, I think you should read some articles about Java memory model for deeper understanding of this.

Cortwave
  • 4,747
  • 2
  • 25
  • 42