As far as I know, threads copy variables in their local cache. What I'm doing is, I'm getting values in the main thread and then I'm consuming them in some other background (renderer) thread. Like this-
class MySurfaceView ... {
private var someValue = 0
// Called from the main thread
fun updateValue() {
someValue++
}
fun render() {
Thread {
// Here someValue variable is consumed
// and it's always up to date.
....
}.start()
}
}
So, inside the runnable passed to the thread started inside render(), 'someValue' is always up to date and I didn't even mark it volatile. If threads copy variables to their local cache then why is it happening? Is it because an implicit reference of the outer class is being kept and the value is coming from there (if this is true, then in cases like this, where I have one generator and multiple consumer threads, would it always be safe to not mark the field which is updated only by the generator thread as volatile? As read/write operations on volatile is costly)? The same thing also happens when I start a coroutine and try access 'someValue' inside it.