What Is the Actual Memory Place for Static Variables

What is the actual memory place for static variables?

Static fields are initialised when a class is loaded 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 that use OSGi, static variables don't live for the whole life of the application. They can be reloaded many times.

How this is implement may be JVM dependent, 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.

Where static is stored in java8 above version?

All code is held in metaspace.

All class metadata is held in metaspace.

All static variables are held in the heap.

So:

In conclusion, where static method, static variables, static class is stored in java8?

The answers are 1) metaspace, and 2) heap. For 3) it depends on what you mean. However the metadata is the only aspect of a static class that has a representation, and that is stored in metaspace.


Note that an application cannot get its hands on the actual method code, class metadata or frame containing the static variables.

Also note that class metadata, method code, and static frames not copied when (for example) objects are created.

So it is moot where they are actually stored.



Some article says static variables, static class can't be deleted by Garbage Collector.

Those articles are incorrect ... if that is what they actually say. The reality is that a class may be garbage collected if it becomes unreachable, but it is not easy to create the conditions in which a class becomes unreachable. So, in practice classes are rarely garbage collected.

Likewise, a classes static variables will become unreachable if the class itself is unreachable. But that is rare too; see above.

But anyway, the logical inference you were trying to make is incorrect. Being in the heap is neither necessary or sufficient for something to be reclaimed by one of the JVM's storage management mechanisms.

  • Things allocated in metaspace can be deleted.
  • Things allocated in the heap won't necessarily ever be eligible for deletion.

When is the memory allocated for a static variable in java?

When the class is loaded, at runtime. You can find the details here.

Where the static variables are stored?

Static variables are stored in Datasegment in the memory. Thier life time is till the program terminates. but their scope is local to the function in which they are declared. if declared global then their scope is limited to the file in which they are declared.

Where are static methods and static variables stored in 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.

Where are static variables stored in C and C++?

Where your statics go depends on whether they are zero-initialized. zero-initialized static data goes in .BSS (Block Started by Symbol), non-zero-initialized data goes in .DATA

Memory allocation to static variables (Compile time memory allocation)

You've misunderstood the statement 'memory allocation at compile time'. What is meant by that is that the compiler writes data to the binary that it produces that indicates that the memory should be set aside when the program is loaded by the operating system.

In particular, the field is usually stored in a section in the output file that is called the BSS. The compiler puts the static variable declaration in the BSS, the OS's program loader reads out the BSS section when loading the program, and sets aside enough memory in the freshly created process to store the BSS.

Every time the program is launched, that is every time a new process is created, new memory is set aside for that process. This includes the memory needed for the BSS aka static variables.

What is the need, local static variables are allocated memory during compile time?

Allocating and initializing the memory at compile time means the program doesn't have to keep track of whether the function has already been entered and the variable has been initialized. Local static variables with constant initial values are treated essentially the same as global variables, except that the name is only in the scope of that function.

It's a time-space tradeoff -- initializing it during the first call would require code that has to be executed every time the function is called. Initializing it when the program is loaded means that its initialization is done as part of the block copy from the executable's text segment to the data segment of memory, along with global statics.

See What is the lifetime of a static variable in a C++ function? for the more complicated case of C++ local static variables. In C++ I would probably use a static std::array, which I don't think would be initialized until the function is entered.

If you have a large array in a function that's rarely called, and you don't want to waste memory for it, use a static pointer instead of a static array, and initialize it yourself.

void func1() {
static int *data;

if (!data) { // Need to protect this with a mutex if multi-threading
data = malloc(N * sizeof(int));
for (int i = 0; i < N; i++) {
data[i] = i;
}
}
...
}

This is the code the compiler would have to generate to do first-time initialization of the array.

In which memory static variables,local variables are presents?

When you do a heap dump you get all the static values. The heap dump shows that static fields are in a special object for that class. You can access this "object" in the Sun/Oracle JVM by using the Unsafe class.

While local values are on the stack, eg. a reference, any object this references in on the heap. (Unlike languages like C++)

e.g.

String hi = "hello";

The reference hi in on the stack but the Object (which is most of the memory) is in the heap.

Memory Allocation of Objects and Non Static Variables in Java

Everything needs a memory location: each Object, each non-static variables and static variables too.

If they don't have a memory location they basically don't exist. The Object needs a memory location as well because otherwise we wouldn't know which non-static variables are related to which objects.



Related Topics



Leave a reply



Submit