1

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 )

1 Answer 1

1

When you pass your Runnable instance to Thread constructor, it will store this object in a private field. When you start your thread, the runnable instance you passed as parameter will be called. And thread will access your test object through this Runnable.(*)

If you want to know, how different threads can have its own copy of Test object You should check ThreadLocal.

Example:

public class Thread1 implements Runnable { 
   // each thread will have it's own copy of test object in this case
   private ThreadLocal<Test> test = new ThreadLocal<Test>();

    public void run() {
        // this line wont affect the others test instance.
        test.set( new Test() );

   }

}

(*) To understand this clearly you can think this as, you are just passing an object to another object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.