If I create a static variable in Java, does it automatically go into the perm gen space on the heap? it seems obvious that the answer is yes, but i cannot find the confirmation anywhere. I know the static variable (also strings and enums) are alive for the life of the JVM so it must go on the permanent heap. IS this correct?
- 2For future, read this post.Sotirios Delimanolis– Sotirios Delimanolis2013-08-29 14:24:41 +00:00Commented Aug 29, 2013 at 14:24
- It depends on JVM's implementation, how is it obvious?rocketboy– rocketboy2013-08-29 14:25:01 +00:00Commented Aug 29, 2013 at 14:25
- Be sure you distinguish between the variable and, if the variable is a reference variable, what object it points to. For a reference the object will be allocated where the object is allocated. As to where the static variable is stored, it would likely be allocated in the same general area as the rest of the Class object. (But note that this might not actually be in GCed heap.)Hot Licks– Hot Licks2013-08-29 15:54:05 +00:00Commented Aug 29, 2013 at 15:54
- (And a static variable is no more "permanent" than the Class that defines it. Classes can be garbage-collected.)Hot Licks– Hot Licks2013-08-29 15:55:15 +00:00Commented Aug 29, 2013 at 15:55
- BTW, what difference does it make? There would be no way for an executing program to exhibit different behavior regardless of where static vars are stored.Hot Licks– Hot Licks2013-08-29 15:56:09 +00:00Commented Aug 29, 2013 at 15:56
2 Answers
The idea of the "PermGen" is completely implementation-dependent, and JVMs are free to handle the "physical" memory management however makes sense to them--they're not even actually required to provide garbage collection!
The PermGen is just a feature of some JVM implementations (including the Sun/Oracle HotSpot JVM for many years), and it's actually being eliminated with a new approach in the Oracle Java 8 JVM. It's quite likely that JVMs that include the concept of a PermGen will put static variables there for performance, but it's entirely up to the programmer.
Comments
Memory that can be shared between threads is called shared memory or heap memory.
All instance fields, static fields and array elements are stored in heap memory. In this chapter, we use the term variable to refer to both fields and array elements. Local variables (§14.4), formal method parameters (§8.4.1) or exception handler parameters are never shared between threads and are unaffected by the memory model.
Nice description here By @Stephen:static allocation in java - heap, stack and permanent generation