How are static fields stored in java?


How are static class fields stored in java? I know that there was such a question. (JAVA) In what memory area are the static fields of the class stored? But it says that they are stored in Permanent Generation. And in java 8, after all, it is replaced by MetaSpace? Are they now stored in MetaSpace? If so, please explain why? After all, MetaSpace is the area where metadata is stored? And static fields are not the same metadata.

Author: Дух сообщества, 2015-11-15

2 answers

And in java 8, after all, it is replaced by MetaSpace?

Yes, if we are talking about HotSpot jvm.

Are they now stored in MetaSpace?

Yes

If so, please explain why? After all MetaSpace is a domain, where is the metadata stored?

MetaSpace is the same PermGen, only with a bun in the form of a dynamic extension. In Permanent Generation, the size limit depended on many factors: the number of classes, methods, the size of the pool of constants, etc. Now the size of the meta space is limited only by the size of the available memory. If we want to change it, then use the MaxMetaspaceSize flag.

Thus, the possibility of java.lang.OutOfMemoryError falling out was eliminated. Well, yes, if you hit the RAM limit, or the limit set in MaxMetaspaceSize, then there will be an exception.

And static fields are not the same metadata.

Mmm. If you look at the book Java Data Objects, then there says that static fields - this is meta data.

 7
Author: Suvitruf - Andrei Apanasik, 2015-11-15 12:50:41

@Suvitruf's answer is generally confusing. Let's say you start a static field:

class MyClass {
    static List<String> myList = new ArrayList<>();
}

In this case, only the reference to the ArrayList object will be stored in Metaspace. And ArrayList itself, of course, will be in the usual heap (as in previous versions of Java). Do not forget that you can then at any time make at least an ordinary non-static field, at least a local variable and assign the same object: List<String> var = MyClass.myList;.

In general, Metaspace is off-heap memory, and Java objects are always located in the pile. Even if the link to them is from the off-heap region.

 4
Author: Tagir Valeev, 2015-11-17 05:59:49