简体   繁体   中英

Java: where do static fields live within the memory?

If we store objects in static fields of an object, how does the JVM allocate the memory for it? Does it live within "implicit"(not sure if I am using the right word) class object? How are static fields different from object fields?

Static fields are class variables, and are shared amongst all instances of that class. Instance variables (or object fields as I think you are referring to them as) belong to individual instances of a class and are not shared.

As for where they are stored in memory is going to based on the implementation of the JVM and there is no reason two different JVMs would be required to store them in the same place by specification (to the best of my knowledge at least - should insert appropriate spec sheet link here).

As Nick's answer says, there is no specific "physical" location stipulated by the language specification, but in terms of a logical mental model that you can reason about, it may help you to think of static fields as being attached to the class object ( Foo.class ) of the class those fields belong to.

As an aside, the class object is used in other ways (that are stipulated by the language spec) when dealing with static entities: for example, when calling a synchronized static method, the lock is held on the class object of the class that method belongs to.

Static fields are part of the class; supposedly, they disappear when the class is unloaded. It makes sense to imagine them as being somewhere close to the Class instance for the class. Details on how memory is laid out are beyond the reach of the Java application; as a corollary, the JVM specification mandates nothing specific on that subject. Even the "disappearance" of the fields when the class is unloaded cannot be observed directly, but only through GC action, assuming a well-placed finalize() method.

Static fields are stored within the Class object, which is kept in PemGen space. This is part of heap memory.

As NickLarsen said, I don't think there is any JVM specification how exactly static fields are stored. Compile defined constants (static final) will replace most likely the expression during compile time. For variable static fields there will be only two options: The heap or (if existing) the data segment of the JVM.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM