• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Stack or Heap

 
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Person ref = new Person();

new Person() tells the jvm to allocatie memory for the new Person object in the heap

Person ref also tells the jvm to allocatie memory for the reference variable ref, is it allocated in the heap or stack?

Thank you
Himalay Majumdar
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Don't know. But it might vary whether it's a field or a local variable.
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My guess is if the reference variable is a local variable, then its in stack memory, but if used as field will be a part of heap. Thanks for your quick insight.
 
Ranch Hand
Posts: 488
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would guess the exact same thing. Isn't the rule that any data on the heap that cannot be referenced in some way from the stack is eligible for garbage collection?
 
Ranch Hand
Posts: 179
Mac Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well the objects are stored on the heap and the references to these objects are stored based on the stack or the heap based on their declaration.
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
An example showing that the reference variable is stored in the heap would be helpful.

Is there anyway java can help us to check if the variable is a part of heap or stack.
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sounds as if a trip to places like the BCEL handbook and the Virtual Machine Specification would be helpful.

But the whole idea of Java is that you don't need to know whether data are stored on the stack or heap or behind the sofa . . .
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
looks like Campbell wants me to keep my mouth shut on this topic

Thanks all
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To add to the mess, with some of the Java 6 and later optimizations, it may not be possible to tell where the object is -- With "escape analysis", the JVM may decide to place certain objects on the stack.

This whole topic is nice and all, but may be moot for future releases of the JVM.

Henry
 
Ranch Hand
Posts: 457
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you understand the computer science basics, there is only one possible answer (it's almost a language neutral question). Having had to learn assembly language on several different processors way "back in the day", I can tell you I have great familiarity with it.

All references that are local variables are pushed onto the stack. They go out of scope, and are reclaimed when the method exits.

All references that are instance variables are part of the object they are within and are implicitly created with that object. If all objects are on the heap, then the reference from within that object is there as well. If there is some stack optimization in a later Java revision then the reference is inside that.

If you need us to give an example of an instance variable � well, then I think I'll wait until you ask for that.
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
My understanding as follows



Instance variable 'height' and 'str' along with the class variable 'var' live inside the object they belong to and hence are in the heap.



variable 'p and 's' being local go in the stack, Person being an object always goes into heap no matter where is reference is declared.

Please correct me if I am wrong anywhere.

Is there an api support , some thing like reflections that allows me to play with the memory, that atleast can tell me given a variable where the is it being stored currently, in heap or stack.

If I shud study the JVM specifications to do that, then I quit.

Thank you all
[ November 25, 2008: Message edited by: Himalay Majumdar ]
 
Ranch Hand
Posts: 490
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is a valid question, just because Java hides it, doesn't mean it is unimportant. Especially if you are in a computer science program.

To be a solid CS or even just plain vanilla programmer, you need to understand what is going on under the hood.

If it is local to a method, the reference will live on the stack. If it is a member of an object it has to be on the heap. If you think about how the stack operates, it would be rather difficult to store persistent data on a stack.
 
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Again, as Henry said, since JDK 6, objects can sometimes be stored on the stack rather than the heap. This is possible if the JVM can prove to itself that no other threads can get a reference to the object, and the last reference to the object goes out of scope when a particular method exits. Then it makes a lot of sense to allocate the memory on the stack rather than the heap, and garbage collection happens automatically when the appropriate method exits.

Basically, anyone who says "objects are always allocated on the heap" is wrong, nowadays. You can say that objects areoften allocated on the heap, or traditionally allocated on the heap. But definitely not always.
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Originally posted by Mike Simmons:
"objects are always allocated on the heap" is wrong, nowadays



yeah..this is something new to know. Do you mean the following.

Person P1 = new Person();

As long as there is one reference to the Person object, it stays in the stack. If I do

1. Person P2 = P1;
Since there are two references to the Person object it moves to the heap.

2. P1 = null;
Just P2 is refers to it, it comes back to stack.

3. P2 = null;
No reference left, and hence it is Garbage Collected from the stack.

Moving an object between heap and stack will ofcourse have many factors to consider, but in general..is this what happening in Java6?
[ November 26, 2008: Message edited by: Himalay Majumdar ]
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Himalay Majumdar:
looks like Campbell wants me to keep my mouth shut on this topic

Thanks all



No, he's trying to cover up for not knowing the answer himself
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Himalay Majumdar:
Instance variable 'height' and 'str' along with the class variable 'var' live inside the object they belong to and hence are in the heap.



Wouldn't the var class variable live inside the .class file rather than the objects? As I said earlier, don't know.
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Being a class variable it should be accessed by the instance variables any time and putting it in the heap seems to be better option.

I dont think instance variable in the heap will point to class variable in the stack.

You are right in asking how a class variable be inside a specific object. I too think it should not be, but again where and how does a class variable gets stored is the question.

Thanks for pointing on that, I was hoping someone would tell me about it.
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Himalay Majumdar:
Thanks for pointing on that, I was hoping someone would tell me about it.

So was I.

I think it lives with the loaded class file, not the objects, but I am not at all sure.

It shows what an interesting discussion you can start by saying "don't know."
 
author
Posts: 9050
21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Rusty said:

If it is local to a method, the reference will live on the stack. If it is a member of an object it has to be on the heap.



I think that for the purposes of the beginner's forum that's probably a pretty good summary. I'm going to go out on a limb, way out, and surmise that even with all the new-fangled compilers and optimizers and thingies that Sun is coming up with, Sun would like you to usually design your stuff with what Rusty said as your perspective.
 
Mike Simmons
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The other option, especially for beginners, is what Campbell said earlier: you simply don't need to know whether data are stored on the stack or heap or behind the sofa. It doesn't matter. (Most of the time.)

Since the original poster is one of the main ones here who seems to want to dig into the details, perhaps it would be appropriate to move this thread out of Beginner, if those details are out of scope for Beginner. My feeling is, if one is going to get into the details, those details may as well be correct.
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Since the thread has moved to which part of the heap you store static fields in, I shall agree with Mike and move it to intermediate.
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Mike Simmons:
you simply don't need to know whether data are stored on the stack or heap or behind the sofa. It doesn't matter. (Most of the time.)

Since the original poster is one of the main ones here who seems to want to dig into the details, perhaps it would be appropriate to move this thread out of Beginner



"Head first java - K & B" which is suppose to be a beginners book clearly tells about storing Instance Variables and Local Variables in heap and stack since begining, but not class variables. So I really dint feel talking about stack,heap and variables is digging into the details.

May be the direction it took afterwards, qualifies it to be a intermediate topic. I am glad . Thanks all.
 
Mike Simmons
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[HM]: Do you mean the following.

Person P1 = new Person();

As long as there is one reference to the Person object, it stays in the stack.


It may be put on the stack - assuming P1 is a local varaible, not an instance variable. It's up to the JVM, which in general doesn't make any guarantees about this, and won't tell us.

[HM]: If I do

1. Person P2 = P1;
Since there are two references to the Person object it moves to the heap.


No, it doesn't matter how many references there are if they're all local variables, which seems to be the case here. When this method exits, they're all going out of scope. So far, the method hasn't done anything that would prevent the JVM from allocating the Person object on the stack rather than the heap.

Also, in general I don't think that objects usuallymove from stack to heap, or vice versa. Rather, the JVM/JIT analyzes the code and decides that for a particular method, a particular object can be allocated on the stack - and then it modifies its internally-loaded code so that whenever that method executes, the object will be allocated on the stack during method execution, then popped off the stack when the method completes. So the object won't move from heap to stack, or vice versa - instead the code will be changed so that the object is always on the stack (until it's popped off, which can be seen as a form of GC). Or always on the heap (until it's GC'd the normal way).

[HM]: 2. P1 = null;
Just P2 is refers to it, it comes back to stack.


No effect - if it was on the stack, it stays on the stack.

[HM]: 3. P2 = null;
No reference left, and hence it is Garbage Collected from the stack.


Hence it's available for Garbage Collection. If it's on the stack, this will probably happen when the method exits. Setting the variable to null matters very little here, as the variable will go out of scope anyway. If it's on the heap, then the object may be collected as soon as the last reference is set to null, or it may be collected much later. Or never.

[HM]: Moving an object between heap and stack will ofcourse have many factors to consider, but in general..is this what happening in Java6?

Nope, no moving, as discussed above.
 
Mike Simmons
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
[HM]: "Head first java - K & B" which is suppose to be a beginners book clearly tells about storing Instance Variables and Local Variables in heap and stack since beginning, but not class variables. So I really dint feel talking about stack,heap and variables is digging into the details.

Yeah - heap and stack have become less beginner-friendly topics since JDK 6 came out. And I'm not even sure where the class variables are stored - not on the stack, certainly, but I don't know if they're part of the Class object, or stored somewhere else in the heap. Again, it's one of those things that usually doesn't matter unless you're building your own JVM implementation (
or hacking an existing one).
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When I started learning java the statement "Person p = new Person()" was always confusing for me, I used to wonder what's going. Both "Head first java" and this discussion has certainly helped me to understand things(objects) in a higher level.

I guess, even Bert should have just got aware of the fact mentioned by Mike that after Java 1.6 "objects are always allocated on the heap" is wrong, nowadays.

Personally, I no longer want to know where the class variable goes . Anyone is welcome to answer though.

Thank you Mike, Campbell and all for your time and patience with the topic.
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're welcome.

And I am quite sure Bert knows there are objects created "on the stack" occasionally, but kept quiet about that because we were on "beginners'". Remember the Head First book was printed before Java 6, and there was no such thing as an object "on the stack" in Java 5.
 
author
Posts: 3285
13
Mac OS X Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Henry Wong:
To add to the mess, with some of the Java 6 and later optimizations, it may not be possible to tell where the object is -- With "escape analysis", the JVM may decide to place certain objects on the stack.

This whole topic is nice and all, but may be moot for future releases of the JVM.

Henry



Whatever will they change next?! Thanks for that Henry I had _no_ idea, yet another one of my safe delusions shattered
 
Bert Bates
author
Posts: 9050
21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
One of the things that we mention in all of our HF books is that we use an "80/20" approach. We assume that if you're going for your PhD, you'll use more than just HF Java as your reference

I'll stand by my statement that for the most part Rusty's summary will stand you in good stead. When Rusty's summary is no longer precise enough for your purposes you will be way past the audience we had in mind for HF Java

That said, I would be interested in hearing about how Rusty's summary wouldn't be good enough for a design decision you might be making. For example, if occasionally an object might be "placed on the stack", how would that knowledge change how you might design a specific bit of code?

hth,

Bert
[ November 27, 2008: Message edited by: Bert Bates ]
 
Mike Simmons
Master Rancher
Posts: 4806
72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Bert, thanks for your reply. I would ask: why is it important to know whether it was on the stack or heap in the first place? And did that affect a given design? (And if so, did it affect that design correctly, now that we know that objects may be allocated on the stack rather than the heap?) Are there really people who need to know this sort of thing, but can't handle the full truth?

I'm thinking that the 80/20 rule is good, but applying it here, it may be better to just drop mention of stack and heap entirely from future versions of HFJ. Or if not that, to at least sprinkle in weasel words like "often", "typically", or, my favorite, "traditionally", rather than absolutes like "always".

I don't have a copy of HFJ before me at the moment, so I don't know whether these concepts were presented in absolutist language, or if that was inferred by readers. And to be fair, a statement like "objects are always allocated on the heap" would have been perfectly true when HFJ2 was written. But things have changed since then. When someone presents a statement in absolutist language that I know to be incorrect, now, I think it's beneficial to fix the problem. Or at least warn people that the discussion is oversimplified. Readers uninterested in the details can choose to accept the simplified discussion - but I hope they'll at least be aware that it's a simplified discussion. If they find themselves revisiting these concepts a year or two later, I'd like them to have some awareness that what they learned originally was not some gospel truth, and that there might be more to the story.
[ November 27, 2008: Message edited by: Mike Simmons ]
 
Himalay Majumdar
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think HFJ presented the concept of life and death of objects using stack and heap in java beautifully.

Its only a point(class variables in heap or stack) that I felt was not covered, but as other said--those details are not needed most of the time.

Things have certainly changed after Java 1.6.
 
Bert Bates
author
Posts: 9050
21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Mike,

I "mostly" agree with you. When it's time to update HF Java we will look at the changes that 6 and maybe 7 bring.

The 80/20 rule is a hard one to implement. A common problem that I see in a lot of technical writing is that when you write to cover all the bases, to cover all the little corner cases, you usually end up creating turgid, over-dense language that blocks learning.

As far as an 80/20 discussion of the stack and heap, I'm pretty sure we'll keep that in the book It's VERY important for programmers to be totally, 100% clear on reference variables, objects, and the basic ideas of garbage collection. Our experience is that a basic understanding of the stack and the heap usually help people to understand these other OO ideas.

hth,

Bert
 
Rusty Shackleford
Ranch Hand
Posts: 490
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry for reviving a slightly old thread.

How could persistent often accessed data permanently reside on the stack? To access it, you pop it off, and the stack pointer no longer points to that stack frame. Constantly pushing and popping the same object seems extremely inefficient.

Or am I missing something important?
 
Campbell Ritchie
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Not sure, but I think objects only go onto the stack when it is clear to the JVM that they are only required briefly, which I think means local variables.

Anybody else?
 
Henry Wong
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Campbell Ritchie:
Not sure, but I think objects only go onto the stack when it is clear to the JVM that they are only required briefly, which I think means local variables.

Anybody else?



The "optimization" that is being referred to here -- objects on the stack -- is called "escape analysis". I believe it is only partially implemented with Java 6, but should be in Java 7. And yes, it applies to local variables.

Basically, the class is examined to see if it can escape a method -- meaning does any of the constructors, init blocks, methods, and even finalizer pass itself elsewhere. And of course, does the methods that uses the class store it elsewhere, etc.

If it can't escape the method, then one of the possible optimizations is to instantiate it on the stack. Apparantly, this actually has an effect, as a large portion of objects instantiated in Java are temporary interim data structures, that are created and thrown away, during processing.

Henry
[ December 17, 2008: Message edited by: Henry Wong ]
 
Greenhorn
Posts: 17
Eclipse IDE Java ME Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Henry,
You have given really nice explanation on very confusing topic..

Just wanted to know one thing..
If it is asked straight away that..'Where class level variables (Static variables) are stored? Stack or Heap?' ..What should be the answer?
I think it should be Heap,am I?
 
reply
    Bookmark Topic Watch Topic
  • New Topic