I understand that objects are stored in heap space. with more details here : https://www.hackerearth.com/practice/notes/runtime-data-areas-of-java/
in the following code the object param the reference of it is stored in thread stack, but the object itself is stored in heap :
private void foo(Object param) {
....
}
To ask my question , At first I will start with code :
public class Thread1 implements Runnable {
Test test = new Test();
public void run() {
test=new Test(); // This will affect other thread , the object reference is changed here
System.out.println(test.id());
}
}
in the code above all the threads from the same instance of Thread1 will have the same reference( let's say variable) of test , which means changing the reference of test will affect other thread:
Runnable runnable=new Thread1();
Thread thread1=new Thread(runnable);
thread1.start();
Thread t2=new Thread(runnable);
thread2.start();
The question here , test will be stored in heap. but how does thread access it ? ( I don't think it will have reference in stack, because changing the value inside thread won't affect the other in this case). if the thread can access that variable directly ( let's say no reference in stack) what scope will it have ? ( I mean shouldn't it be limited to it's own variable )