import org.joda.time.LocalDate;
public class Test {
public static void main(String[] args) {
long time=System.currentTimeMillis();
new LocalDate(2000,1, 1);
System.out.println(System.currentTimeMillis()-time);
time=System.currentTimeMillis();
new LocalDate(2000,1, 1);
System.out.println(System.currentTimeMillis()-time);
}
}
The first call to new LocalDate takes 110ms.
The second call takes 0ms.
Firstly how do I run all the static initializers for a given class?
Secondly, is there a way to do this for all classes my application references in advance?
My application is very latency sensitive.
You can get a list of classes loaded with
-XX:+TraceClassLoadingand save this to a file.You can then use Class.forName() to ensure all these classes have loaded.
This will load every class and ensure their static blocks have been loaded.
However for latency sentive code, you really need to ensure it has been compiled by warming it up (i.e. calling it enough times to trigger compilation) This can reduce latency by a further factor of 10 or more.
If you run
prints
Trying to create an instance won’t load the class more. It may load the default constructor if it has one, but that will only help if thats the one you want.