I know there are many topics and resources about this, but I'm wondering about a very specific question (and it might take a very long time to check all sources for a definite answer).
I know that JVM/Dalvik guarantees that by the time you access a static field of a class (except for final static
primitive values), the static fields of the class are already initialized. Is the opposite true as well? If I never access a class at all (e.g. because the switch-case
code in another static method never reaches a certain branch), is it guaranteed that the VM does not initialize statics of this class?
Assume I have a class such as this:
public class Boo {
public static int[] anything = new int[] { 2,3,4 };
private static int[] something = new int[] { 5,6,7 }; // this may be much bigger as well
public static final int[] getAndClear() {
int[] st = something;
something = null;
return st;
}
}
My application is a very special one (not typical in some aspects), and it may hold hundreds of classes such as Boo
(generated by a code generator), where something
may be an array of varying element count (so it may contain very many elements as well sometimes).
Depending on application input, many of these pregenerated classes might never get accessed. I do not want that a lot of int[]
objects get initialized unnecessarily, eating up much memory.