144

For example:

class A {
    static int i=0;
    static int j;

   static void method() {
       // static k=0; can't use static for local variables only final is permitted
       // static int L;
    }
}

Where will these variables be stored in Java, in heap or in stack memory? How are they stored?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Nav
  • 10,304
  • 20
  • 56
  • 83
  • 3
    very useful link to understand Garbage collection on Oracle's Official website: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html – Arnav Joshi Sep 25 '16 at 18:04

11 Answers11

180

Static methods (in fact all methods) as well as static variables are stored in the PermGen section of the heap, since they are part of the reflection data (class related data, not instance related). As of Java 8 PermGen has been replaced by MetaSpace and as per JEP 122 it only holds meta-data while static fields are stored in the heap.

Note that this mostly applies to Oracle's Hotspot JVM and others that are based on it. However, not every JVM has PermGen or Metaspace like Eclipse OpenJ9.

Update for clarification:

Note that only the variables and their technical values (primitives or references) are stored in PermGen space.

If your static variable is a reference to an object that object itself is stored in the normal sections of the heap (young/old generation or survivor space). Those objects (unless they are internal objects like classes etc.) are not stored in PermGen space.

Example:

static int i = 1; //the value 1 is stored in the PermGen section
static Object o = new SomeObject(); //the reference(pointer/memory address) is stored in the PermGen section, the object itself is not.

A word on garbage collection:

Do not rely on finalize() as it's not guaranteed to run. It is totally up to the JVM to decide when to run the garbage collector and what to collect, even if an object is eligible for garbage collection.

Of course you can set a static variable to null and thus remove the reference to the object on the heap but that doesn't mean the garbage collector will collect it (even if there are no more references).

Additionally finalize() is run only once, so you have to make sure it doesn't throw exceptions or otherwise prevent the object to be collected. If you halt finalization through some exception, finalize() won't be invoked on the same object a second time.

A final note: how code, runtime data etc. are stored depends on the JVM which is used, i.e. HotSpot might do it differently than JRockit and this might even differ between versions of the same JVM. The above is based on HotSpot for Java 5 and 6 (those are basically the same) since at the time of answering I'd say that most people used those JVMs. Due to major changes in the memory model as of Java 8, the statements above might not be true for Java 8 HotSpot - and I didn't check the changes of Java 7 HotSpot, so I guess the above is still true for that version, but I'm not sure here.

Thomas
  • 87,414
  • 12
  • 119
  • 157
  • 1
    Ahh are you sure about static variables? AFAIK PermGen only stores the definitions not the actual value. – Amir Raminfar Dec 05 '11 at 15:58
  • 2
    @Amir I'm pretty sure that the variable itself is stored in the permgen space, any referenced object will most likely be allocated on the heap. This might add some information: http://stackoverflow.com/questions/3800444/where-does-a-static-final-directly-allocated-into-young-gen-or-old-gen-or-per – Thomas Dec 05 '11 at 16:01
  • 1
    Ah yes the variable definition is stored in permgen. But the value will be in the heap. Your answer suggested that the value is also stored in PermGen. – Amir Raminfar Dec 05 '11 at 16:02
  • @Thomas I agree with your comment, but that's not what your answer says. – Matthew Farwell Dec 05 '11 at 16:03
  • 1
    @Matthew how do you understand my answer? A said that _variables_ are stored in the permgen section (primitives/references) not the objects they refer to. It depends on how you view a variables _value_. – Thomas Dec 05 '11 at 16:05
  • If static methods and variables both are stored on the heap ...does that mean that gc() will clean them from the memory once the execution of all statements using these variables are complete. Or would I have to initialize them and null and then call System.gc(). – Nav Dec 05 '11 at 16:05
  • 2
    @Nav not all parts of the heap are garbage collected by default and sometimes classes and thus static variables can't be collected since class loaders still have a reference on them. Additionally you shouldn't rely on the garbage collector to run since that's totally up to the JVM (it decides when to run and what to collect, you can only provide hints like "I'd like you to run gc now" :) ). – Thomas Dec 05 '11 at 16:09
  • I just read it somewhere on a blog that said if I initialize a static variable as null then it makes it eligible for garbage collection as they then become unused members so finalize() can be called on them and then gc will clean that memory..I just wanted to know if that is true...cause I had some doubt about it :-o – Nav Dec 05 '11 at 16:16
  • @Thomas I understood your answer and agree with it, but it implies that objects that are referred to by static variables are allocated in permgen, which is incorrect, and probably not even possible to enforce. Just a comment about the way the answer is worded, that's all. – Matthew Farwell Dec 05 '11 at 16:23
  • Poke Poke ..can I have the answer to my question "I just read it somewhere on a blog that said if I initialize a static variable as null then it makes it eligible for garbage collection as they then become unused members so finalize() can be called on them and then gc will clean that memory..I just wanted to know if that is true" :( – Nav Dec 05 '11 at 16:34
  • @Nav see my update, technically a (static) variable can't be collected but the object it references. Thus if you set a variable to null you just remove one reference to that object and if there are no more references the gc run _might_ collect it and it will then invoke `finalize()` _once_ (if it had not already been invoked but failed). As I said in my answer, _don't rely on finalize()_. – Thomas Dec 05 '11 at 16:37
  • I didn't know finalize() method runs only once on the same object...thanks guys now I can sleep in peace...this link had me up the whole day http://www.codeguru.com/forum/printthread.php?t=362966 (see the post in the link by randomjunk)as I had some serious doubt about it B-) now I am clear – Nav Dec 05 '11 at 16:42
  • @Nav I just skimmed over that link and it isn't wrong. However, as with every explanation, it might be misunderstood. What they mean is: if you assign an object to a static variable you get a reference that most likely won't vanish since the object it belongs to won't be collected (due to it being a class and thus being held by the class loader). If you assign null to the variable you remove the reference to the object which now might be garbage collected. The static variable itself, however, will still be there (with a value of null now). Hope that makes it somewhat clearer. Sleep well :) – Thomas Dec 05 '11 at 16:57
  • 1
    `Static methods (in fact all methods) as well as static variables are stored in the PermGen section of the heap, since they are part of the reflection data (class related data, not instance related).` Can you please quote the official link for that? – Mac Jun 13 '14 at 11:54
  • @Mac I don't have an _official_ link but you should be able to find that in the HotSpot JVM spec. – Thomas Jun 13 '14 at 12:53
  • 1
    PermGen is not necessarily to be a part of Heap area. Just wanted to point out for clarity. – stdout Oct 11 '15 at 15:20
  • @Thomas Regarding the link for the documentation Mac mentioned, I could not find the HotSpot documentation. I did find the JVM spec (https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-2.html#jvms-2.5) but it doesn't seem to be discussed there... – flow2k Oct 08 '17 at 21:09
  • @flow2k note that what you linked is the spec for Java 8 which doesn't have permgen space anymore (the new thing is metaspace but I'm not that familiar with it yet). – Thomas Oct 09 '17 at 08:20
  • @Thomas Interesting - I didn't even know that; you're right about permgen - https://stackoverflow.com/questions/18339707/permgen-elimination-in-jdk-8. – flow2k Oct 09 '17 at 22:03
  • @Thomas is the place where static members are stored the same in different implementation of JVM ? Or your statement for PermGen (now MetaSpace) is right only for HotSpot? Thanks! – Ruslan Dec 11 '18 at 23:08
  • 1
    @Ruslan that probably depends on whether the JVM uses a permanent generation or metaspace. So far all JVMs I used (that's mainly Sun/Oracle JDK and some OpenJDKs) used the PermGen or Metaspace to store the metadata but [this proposal](http://openjdk.java.net/jeps/122) to remove PermGen states that JRockit had no PermGen - so it seems it depends on the JVM implementation. I also couldn't find any specification stating how and where the class metadata (which includes the definitions of the static fields) has to be stored - that could mean I've just not found it or that it's up to the JVM vendor – Thomas Dec 12 '18 at 12:27
41

Prior to Java 8:

The static variables were stored in the permgen space(also called the method area).

PermGen Space is also known as Method Area

PermGen Space used to store 3 things

  1. Class level data (meta-data)
  2. interned strings
  3. static variables

From Java 8 onwards

The static variables are stored in the Heap itself.From Java 8 onwards the PermGen Space have been removed and new space named as MetaSpace is introduced which is not the part of Heap any more unlike the previous Permgen Space. Meta-Space is present on the native memory (memory provided by the OS to a particular Application for its own usage) and it now only stores the class meta-data.

The interned strings and static variables are moved into the heap itself.

For official information refer : JEP 122:Remove the Permanent Gen Space

Manish Kumar
  • 411
  • 4
  • 2
29

Class variables(Static variables) are stored as part of the Class object associated with that class. This Class object can only be created by JVM and is stored in permanent generation.

Also some have answered that it is stored in non heap area which is called Method Area. Even this answer is not wrong. It is just a debatable topic whether Permgen Area is a part of heap or not. Obviously perceptions differ from person to person. In my opinion we provide heap space and permgen space differently in JVM arguments. So it is a good assumption to treat them differently.

Another way to see it

Memory pools are created by JVM memory managers during runtime. Memory pool may belong to either heap or non-heap memory.A run time constant pool is a per-class or per-interface run time representation of the constant_pool table in a class file. Each runtime constant pool is allocated from the Java virtual machine’s method area and Static Variables are stored in this Method Area. Also this non-heap is nothing but perm gen area.Actually Method area is part of perm gen.(Reference)

enter image description here

Aniket Thakur
  • 66,731
  • 38
  • 279
  • 289
  • is method area not a subset of the PermGen section of the memory? Why have you shown method area as part of the non-heap memory when, i think, they (PermGen along with method(class) area) are part of the larger heap area of the JVM? – Kaveesh Kanwal Feb 18 '15 at 14:50
  • Read the last line - `Also this non-heap is nothing but perm gen area.Actually Method area is part of perm gen.` – Aniket Thakur Feb 18 '15 at 18:32
  • 1
    @AniketThakur you have shown method area as part of non-heap memory but according to oracle docs, here, https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.5.4 , it is mentioned that method area is logically part of the heap. – Karan Feb 14 '17 at 18:35
17

This is a question with a simple answer and a long-winded answer.

The simple answer is the heap. Classes and all of the data applying to classes (not instance data) is stored in the Permanent Generation section of the heap.

The long answer is already on stack overflow:

There is a thorough description of memory and garbage collection in the JVM as well as an answer that talks more concisely about it.

Community
  • 1
  • 1
Vasiliy Sharapov
  • 997
  • 1
  • 8
  • 27
10

It is stored in the heap referenced by the class definition. If you think about it, it has nothing to do with stack because there is no scope.

Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123
5

In addition to the Thomas's answer , static variable are stored in non heap area which is called Method Area.

Vipin
  • 4,851
  • 3
  • 35
  • 65
4

As static variables are class level variables, they will store " permanent generation " of heap memory. Please look into this for more details of JVM. Hoping this will be helpful

Ramesh Papaganti
  • 7,311
  • 3
  • 31
  • 36
1

When we create a static variable or method it is stored in a special area on the heap: PermGen(Permanent Generation), where it lays down all the data applying to classes(non-instance data).

Starting from Java 8 the PermGen became - Metaspace.

The difference is that Metaspace is an auto-growing space, while PermGen has a fixed Max size, and this space is shared among all of the instances. Plus the Metaspace is a part of a Native Memory and not JVM Memory.

You can look into this for more details.

viren shah
  • 183
  • 2
  • 8
1

In real world or project we have requirement in advance and needs to create variable and methods inside the class , On the basis of requirement we needs to decide whether we needs to create

  1. Local ( create n access within block or method constructor)
  2. Static,
  3. Instance Variable( every object has its own copy of it),

=>2. Static Keyword will be used with variable which will going to be same for particular class throughout for all objects,

e.g in selenium : we decalre webDriver as static => so we do not need to create webdriver again and again for every test case

Static Webdriver driver

(but parallel execution it will cause problem, but thats another case);

Real world scenario => If India is class, then flag, money would be same for every Indian, so we might take them as static.

Another example: utility method we always declare as static b'cos it will be used in different test cases. Static stored in CMA( PreGen space)=PreGen (Fixed memory)changed to Metaspace after Java8 as now its growing dynamically

ANUP SAJJAN
  • 1,458
  • 13
  • 17
1

static variables are stored in the heap

C.LS
  • 1,319
  • 2
  • 17
  • 35
0

As of Java 8 , PermGen space is Obsolete. Static Methods,Primitives and Reference Variables are stored in Java MetaSpace. The actual objects reside in the JAVA heap. Since static methods never get out of reference they are never Garbage collected both from MetaSpace and the HEAP.

kushagra deep
  • 462
  • 6
  • 12