wood burning stoves 2.0*
The moose likes Threads and Synchronization and the fly likes stack memory Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "stack memory" Watch "stack memory" New topic
Author

stack memory

jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 576
In java ,parameters inside methods are in stack ,all instance variable exist in heap memory.so whatever things written inside a method not affected when many threads access the class.

my question is as follow

1)
if create a object which has instance variable, inside a method then it will exist in heap memory or stack?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18843
    
  40


if create a object which has instance variable, inside a method then it will exist in heap memory or stack?


You need to understand the difference between an object and a reference to an object. An object is always on the heap (there is an exception, but let's not get into that ... ). A reference, can be on the heap, if it is part of the object, such as an instance variable. Or it can be on the stack, when it is declared locally, such as a local variable or a parameter.

Now as for your question...

There is no such thing as an instance variable inside a method. Variables declared inside a method are local variables.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
jacob deiter
Ranch Hand

Joined: Apr 02, 2008
Posts: 576
if object reference variable inside a method,if many thread access the object
then

local object state is not distributed by other threads because object reference variable is local ?
or
local object state is distributed by other threads because object is in heap ?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18843
    
  40

local object state is not distributed by other threads because object reference variable is local ?
or
local object state is distributed by other threads because object is in heap ?


Again, you need to understand the difference between an object and a reference to an object.

Each method will have a local variable which will have there own copy of the reference. This reference will point to an object on the heap. Now... this reference can point to a privat copy of the object -- if it is instantiated in the method. Or it can point to a object, that all objects refer to.

Just because an object is on the heap, doesn't mean that it is shared. It depends on how you coded your application.

Henry
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: stack memory