Where are static methods and static variables stored in Java?

JavaJvm

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

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.

Solution 5 - Java

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.

Solution 6 - Java

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

Solution 7 - Java

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

Solution 8 - Java

static variables are stored in the heap

Solution 9 - Java

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

Solution 10 - Java

When we create a static variable or method it is stored in the special area on heap: PermGen(Permanent Generation), where it lays down with all the data applying to classes(non-instance data). Starting from Java 8 the PermGen became - Metaspace. The difference is that Metaspace is 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.

Solution 11 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNavView Question on Stackoverflow
Solution 1 - JavaThomasView Answer on Stackoverflow
Solution 2 - JavaManish KumarView Answer on Stackoverflow
Solution 3 - JavaAniket ThakurView Answer on Stackoverflow
Solution 4 - JavaVasiliy SharapovView Answer on Stackoverflow
Solution 5 - JavaAmir RaminfarView Answer on Stackoverflow
Solution 6 - JavaVipinView Answer on Stackoverflow
Solution 7 - JavaRamesh PapagantiView Answer on Stackoverflow
Solution 8 - JavaC.L.SView Answer on Stackoverflow
Solution 9 - JavaDurjan SinghView Answer on Stackoverflow
Solution 10 - Javaviren shahView Answer on Stackoverflow
Solution 11 - Javakushagra deepView Answer on Stackoverflow