Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
    Bookmark Topic Watch Topic
  • New Topic

How a method on stack knows that to which object on heap it is connected?  RSS feed

 
guriqbal sandhu
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Report post to moderator
if there are two threads, A and B, and if thread A calls a method-method1 on an object and while the method1 is running the Thread B sets the reference ( the same reference which thread A used to call the method1) to a new object.
Then shall the method1 now have access to the instance variables of new object or the old object with which it was invoked.

class Test
{
int i;
Test(int j)
{
i=j;
}
public void method1()
{
if(!i==i)
{
sysout("something wrong");
}
}
}

Class Test2{
Test1 test1= new Test(0);

public void init()
{ test1=new Test(20);}

public void callToMethod1()
{
test1.method1();
}

}
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Report post to moderator
No. You're overcomplicating it. Thread A looks at some shared variable, and gets its value. That value is a reference. TA uses that reference to invoke some method. While that method is running, TB changes the value of the shared reference variable, so now that variable points to a different object. But TA doesn't know or care, because it has already evaluated that variable's value and found the object it pointed to at that time. It was done with the shared variable before it ever called the method.

Of course, if TA does

and somewhere in the middle of that, TB comes along and changes the value of obj.var so it points to a different object, then, TA's x() call will be on one object and its y() call will be on a different one, because it had to evaluate obj.var twice.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Report post to moderator
Guriqbal, in the future, please CarefullyChooseOneForum and post your question only once.
 
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!