Heap vs Stack vs Perm Space

23,983

Solution 1

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

Solution 2

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

Share:
23,983
caarlos0
Author by

caarlos0

Site Reliability Engineer at TOTVS Labs.

Updated on July 09, 2022

Comments

  • caarlos0
    caarlos0 almost 2 years
    • 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?
  • Daniel C. Sobral
    Daniel C. Sobral almost 13 years
    Stack also stores primitive literals.
  • Kowser
    Kowser almost 13 years
    @Daniel: Thanks for the info. I didn't know that, and I will study more about it.
  • Angel O'Sphere
    Angel O'Sphere almost 13 years
    @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.
  • Angel O'Sphere
    Angel O'Sphere almost 13 years
    @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.
  • Daniel C. Sobral
    Daniel C. Sobral almost 13 years
    @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?
  • Kowser
    Kowser almost 13 years
    @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.
  • Kowser
    Kowser almost 13 years
    @Daniel: You might be interested too. Please see the link above.
  • Daniel C. Sobral
    Daniel C. Sobral almost 13 years
    @Kowser Thanks. Pretty much what I recalled.
  • Angel O'Sphere
    Angel O'Sphere almost 13 years
    @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, though
  • Daniel C. Sobral
    Daniel C. Sobral almost 13 years
    @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".
  • Daniel C. Sobral
    Daniel C. Sobral almost 13 years
    @Angel Back to the JVM, what do you think happens when it executes the opcode iconst_1?
  • Angel O'Sphere
    Angel O'Sphere almost 13 years
    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.