What is the actual memory place for static variables?

Static variable is allocated for the entire duration of program's execution, so neither stack nor heap are convenient for it. Then where is it? There should be some place where it is loaded ?


Static fields are initialised when a class is loaded and and are discarded when the classloader for that class is unloaded. They can be cleaned up, even duplicated in another class loader.

For applications like those this use OSGi, static variables don't live for the life of the application can be reloaded many times.

How this is implement may be JVM dependant but the Sun/Oracle JVM creates an "object" to hold the static fields for a class. This object is accessible via the Unsafe class which can also be used to examine this "objects" fields.


We have 3 segments in our memory:

  • Stack Segment — contains local variables and Reference variables (variables that hold the address of an object in the heap).

  • Heap Segment — contains all created objects in runtime, objects only plus their object attributes (instance variables).

  • Code Segment — the segment where the actual compiled Java bytecodes resides when loaded. Static members (variables or methods) are called class members, meaning they reside where the class (bytecode) resides, which is in the Code Segment.


  • Static variable is allocated for the entire duration of program's execution, so neither stack nor heap are convenient for it.

    In fact, static frames (ie the frames that hold the static variables) ARE allocated from the heap.

    And they don't necessarily exist for the duration of a program's execution. For instance, static frames for classes that are dynamically loaded can be garbage collected if the parent classloader, all classes and all instances becomes unreachable.

    链接地址: http://www.djcxy.com/p/82856.html

    上一篇: 哪里java静态变量存储在内存中?

    下一篇: 什么是静态变量的实际内存空间?