Heap vs Stack vs Perm Space
Asked Answered
K

2

42
  • What are the differences between the Java memory spaces (Perm Space, Space Stack, Heap Space)?
  • When does the JVM use one or another?
  • If I use Scala/Groovy/etc., are there differences?
Krieg answered 23/7, 2011 at 16:13 Comment(5)
Related: https://mcmap.net/q/262362/-perm-space-vs-heap-space, https://mcmap.net/q/48146/-what-is-perm-spaceEllamaeellan
The stack is an implementation detail. May not be just as important for Java since it lacks user-defined value types, but still an important read for everyone working in a garbage-collected language.Puerile
other JVM languages use the same standard?Krieg
Also of note, not all JVMs use PermSpace.Vigesimal
All JVM languages use the same standard, it has nothing to do with the language it is teh JVM!! that is divided into heap and stack space and the heap space is divided into younger and older generations and perm gen.Stricken
D
92

Simply

  • Heap space: All live objects are allocated here.
  • Stack space: Stores references to the object for variable in method call or variable instantiation.
  • Perm space: Stores loaded classes information

For example:

Student std = new Student();

after executing the line above memory status will be like this.

  • Heap: stores "new Student()"
  • Stack: stores information about "std"
  • Perm Space: stores information about Student class
Dearing answered 23/7, 2011 at 16:46 Comment(11)
Stack also stores primitive literals.Fikes
@Daniel: Thanks for the info. I didn't know that, and I will study more about it.Dearing
@Daniel: Stack also stores primitive literals. What do you mean with that? Strictly speakgin the Stack does not store anything On the stack are only parameters to method calls and "values" that are used in evaluating expressions.Stricken
@Kowser: normal java objects, especialy interned Strings also wander over various gc phases into perm gen. The odler an object is the more it moves towards perm gen and finally resides in perm gen.Stricken
@Angel A Stack, by definition, is a data structure that stores stuff, with the property that when you take stuff out, you do it in the reverse order of when you put them in. So, strictly speaking, a stack stores stuff. The stuff that JVM puts in the staff are references to objects and primitive literals. That is, every parameter or variable that is of a primitive type is not put on the stack as references, but as literals. By the way, nothing I saw ever suggested to me that an object could "migrate" to perm gen, do you have a reference to back that up?Fikes
@Angel: redstack.wordpress.com/2011/01/06/… Till now this is the article which I found very easy & well explained on Garbage Collection. Just added it as reference which might be helpful.Dearing
@Daniel: You might be interested too. Please see the link above.Dearing
@Daniel, sorry to be nitpicking but the Satastructure Stack as in java.util.Stack has absolutely nothing to do with "the stack" in a JVM or how a stack works in a real computer, except that it is a LIFO structure. So AGAIN: on a stack in a JVM is NOTHING stored. A stack is for passing parameters to called methods, that is all. Perhaps looking at how byte codes work and how the the JVM is specified or looking at a real assembler for a real processor might help to understand that. Kowser: thanx for the link ;D I know how GCs work, I miplemented a few myself when I was younger. Nice Link, thoughStricken
@Angel I was not talking about java.util.Stack, I was talking about stack. If stuff wasn't stored in the stack, how could you retrieve it from the stack? If you want to speak of assembler instead of the stack concept, the push opcode on i386 stores data in the stack -- it adjusts a register and then writes the data to the position in memory pointed by it. This very act of writing to memory was called in some assembly languages (such as 6502's) store. I'm beginning to think you have some special definition for the word "store".Fikes
@Angel Back to the JVM, what do you think happens when it executes the opcode iconst_1?Fikes
To both of you: that is exactly what I wanted to point out. The original question is allready wrong. The question should have been: for what does the VM use the heap and for what the stack. Note the word use. That is why I said: strictly speaking! Daniel still "thinks" a processor stack is the same as a "datastructure", which is not the case. And yes iconst_1 is an opcode that loads the value 1 on top of the stack! Hence: it is in the sense of the word: not storing anything. The stack is a piece of memory needed for execution. It is not a storage. But perhaps I'm to academic for you.Stricken
A
15

Forgive me for adding an answer to such an old question - The current answer is great, but misses a couple of edge cases because of static code and Java 8 updates.

Overview

  • Stack
    • Allocated per Thread
    • Stores local references and primitives
    • This is scoped memory - When a method or thread ends, all their data in the stack is lost
    • Has the fastest access, so a local primitive is faster to use than a local Object
  • Heap
    • All allocated object instances exist here
    • Divided into Generations, with the youngest generation being the first place GC looks
    • Available to all threads so allocations and deallocations should be synchronised
    • This memory can become fragmented (but you do not usually manage this yourself)
  • PermGen
    • Stores loaded class information
    • Stores immutable information (Primatives, interned Strings)
    • Stores static class members

Example Code

public class SimpleVal { //The Class (loaded by a classloader) is in the PermGen

    private static final int MAGIC_CONSTANT = 42; //Static fields are stored in PermGen
    private static final SimpleVal INSTANCE = new SimpleVal(1); //Static field objects are created in the heap normally, with the reference in the PermGen ('class statics' moved to the heap from Java 7+)
    private static SimpleVal previousInstance; //Mutable static fields also have their reference in PermGen so they can easily cause memory leaks

    private int value; //Member variables will be part of the heap

    public SimpleVal(int realValue) {
        value = realValue;
        ...
    }

    public static int subtract(SimpleVal val1, SimpleVal val2) {
         ....
    }

    public int add(SimpleVal other) { //Only one copy of any method (static or not) exists - in PermGen
         int sum = value + other.value; //Local values in methods are placed in the Stack memory
         return sum;
    }

}

public static void main(String[] args) {

    SimpleVal val1 = null;
    SimpleVal val2 = new SimpleVal(3); //Both of these variables (references) are stored in the Stack 

    val1 = new SimpleVal(14); //The actual objects we create and add to the variables are placed in the Heap (app global memory, initially in the Young Gen space and later moved to old generation, unless they are very large they can immediately go old gen)

    int prim = val1.add(val2); //primitive value is stored directly in the Stack memory
    Integer boxed = new Integer(prim); //but the boxed object will be in the heap (with a reference (variable) in the Stack)

    String message = "The output is: "; //In Java 7+ the string is created in the heap, in 6 and below it is created in the PermGen
    System.out.println(message + prim);

}

Java 8 Note: PermGen space was replaced with what is called Metaspace. This still functions the same but can be resized automaticlly - by default Metaspace auto increases its size in native memory up to a maximum (specified in JVM params), but PermGen always has a fixed maximum size contiguous to the heap memory.

Android Note: From Android 4.0 (from 3.0 in practice) Android should honour the described memory contracts - but on older versions the implementation was broken. The 'Stack' memory in Android-Davlik is in fact register based (instruction sizes and counts vary between the two, but for a developer the functionality remains the same).

Finally, for more info the best answer I've ever seen to this subject on StackOverflow is here

Alber answered 9/9, 2017 at 21:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.