I used to believe that any variable that is shared between two threads can be cached thread-locally and should be declared mutable. But this belief has recently been challenged by a teammate. We are trying to find out if volatile is required in the following case or not.
class Class1 { void Method1() { Worker worker = new Worker(); worker.start(); ... System.out.println(worker.value);
Now I argue that it is possible that the Worker (child) stream could cache the variable "value" of the Worker object in the stream and only update it when copying when setting the value 1. In this case, the main stream may not see the updated value.
But my teammate believes that since access to the "value" occurs through the object (worker), therefore for both threads to view different values this is possible only if both threads support separate copies of the "worker" "object itself ( which also means that creating a stream involves creating a deep copy of all common objects).
Now I know that this cannot be true, since for each thread it would be extremely inefficient to maintain completely different copies of all common objects. Therefore, therefore, I seriously doubt it. Does "worker.value" in the main thread reference a different memory location than "this.value" in the child thread? Will the child (worker) cache be “value”?
Sincerely.
source share