A static field in a class. Is it re-created for every call to a static method?
If I have a static class with a static field, for example:
private static myField = new myObject();
Then I have a bunch of static methods that use myField
.
Is it myField
re-created for every method call? My guess is that it instantiated the first time a method is called that uses it and it stays in memory until the GC clears it?
Cheers for any pointers :-)
a source to share
The static field initializer runs once for a given application domain, and the field remains available for the life of the program. CG will not collect the object referenced by the static member variable.
If the class has a static constructor, then the static field initializer is executed immediately before that constructor, which occurs the first time a static member is accessed or an instance constructor is executed. If no static constructor exists, then the field is initialized at some unspecified time before any static members or instance constructors are executed.
a source to share
It is assigned only once, during class initialization. This happens the first time the class is "actively" touched. See class initialization in the JVM specification for exact information on when the class will be initialized.
Assuming the class this code is in is called MyClass, myField will be GCed shortly after the classloader that loaded MyClass GCed. (classes are unloaded with classloader granularity in all major JVMs).
a source to share