Где хранятся статические переменные java

Understanding storage of static methods and static variables in Java

In every programming language, memory is a vital resource and is also scarce in nature. Hence it’s essential that the memory is managed thoroughly without any leaks. Allocation and deallocation of memory is a critical task and requires a lot of care and consideration. In this article, we will understand the storage of static methods and static variables in Java. Java Virtual Machine(JVM) is an engine that provides a run time environment to drive the java code. It converts the java byte code into machine language. The JVM has two primary functions. They are:

  1. It allows java programs to run on any device or OS to fulfil WORA (Write Once Run Anywhere) principle.
  2. It manages and optimizes program memory.

The JVM memory manager creates memory pools during the runtime of the program. Let’s understand the concept of memory pools in java. There are two types of memory pools namely the stack memory and the heap memory. The main difference between stack memory and the heap memory is that the stack is used to store only the small datatypes whereas heap stores all the instances of the class. And, since java either implicitly or explicitly extends the class from Object.class, every class we create is a collection of objects. This also means that we cannot use a method or a variable unless we instantiate it with a new keyword. As soon as we instantiate the methods, JVM allocates some memory on the heap and it stores the address of the instance on the stack. After this, the methods and variables can be used. In order to get a better understanding of how the new keyword works, let’s take an example. Let’s take a bird class. Whenever a new bird is found, the number of birds need to be incremented. Let’s try to implement this code:

Читайте также:  Обработка ошибок на питоне

Источник

Как в java хранятся статические поля?

Как в java хранятся статические поля класса? Знаю что был такой вопрос. (JAVA) В какой области памяти хранятся статические поля класса? Но там сказано что они хранятся в Permanent Generation. А в java 8 ведь он заменен на MetaSpace? Хранятся ли они теперь в MetaSpace? Если да, объясните пожалуйста, почему так? Ведь MetaSpace это область, в которой хранятся метаданные? А статические поля не являются же метаданными.

2 ответа 2

А в java 8 ведь он заменен на MetaSpace?

Да, если мы говорим о HotSpot jvm.

Хранятся ли они теперь в MetaSpace?

Если да, объясните пожалуйста, почему так? Ведь MetaSpace это область, в которой хранятся метаданные?

MetaSpace — это та же PermGen, только с плюшкой в виде динамического расширения. В Permanent Generation предельный размер зависел от многих факторов: количество классов, методов, размер пула констант и т.п. Теперь размер мета пространства ограничен лишь размеров доступной памяти. Если хотим поменять, то юзаем флаг MaxMetaspaceSize .

Таким образом исключили возможность выпадения java.lang.OutOfMemoryError . Ну да, если вы упрётесь в предел RAM, или в предел заданный в MaxMetaspaceSize , то исключение будет.

А статические поля не являются же метаданными.

Ммм. Если посмотреть книгу Java Data Objects, то там сказано, что статические поля — это мета данные.

Источник

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.

Читайте также:  Python синтаксис для егэ

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.

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.

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. 

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.

Читайте также:  Html and css logo

Источник

Оцените статью