Reputation: 21981
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.
Upvotes: 0
Views: 645
Reputation: 533500
You can get a list of classes loaded with -XX:+TraceClassLoading
and 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
public class CallStatic {
public static void main(String... args) throws ClassNotFoundException {
Class.forName("Static");
}
}
class Static {
static {
System.out.println("static block run");
}
}
prints
static block run
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.
Upvotes: 2
Reputation: 2939
Looks like static initialization issue. Try do
Class.forName("org.joda.time.LocalDate");
before your calls. This should decrease timing. Probably you will need to force other related classes to be loaded. This will not help if the issue is dynamic initialization.
Upvotes: 0
Reputation: 32407
This is just how Java and the JVM works - it always needs a warm-up before running optimally. You should make some integration tests that exercise all the parts of your application, preferably in a way that's non-destructive to data. Then run them against the application each time you deploy it. This will have a bonus of reassuring you that the application is working.
Upvotes: 2