File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Threads and Synchronization and the fly likes How a method on stack knows that to which object on heap it is connected? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Reply locked New topic
Author

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

guriqbal sandhu
Greenhorn

Joined: Oct 07, 2011
Posts: 8
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

Joined: Jan 03, 2004
Posts: 3133
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

Joined: Jan 03, 2004
Posts: 3133
Guriqbal, in the future, please CarefullyChooseOneForum and post your question only once.
 
 
subject: How a method on stack knows that to which object on heap it is connected?
 
Threads others viewed
How a method on stack knows that to which object on heap it is connected?
in Overriding
Dynamic polymorphism and Overriding
overridden method
static methods
IntelliJ Java IDE