Eager java class loading

If you want to force the classes to be loaded do something like this:

public class Main
{
    static
    {
        loadClasses();
    }

    public static void main(final String[] argv)
    {
        // whatever
    }

    private static void loadClasses()
    {
        final String[] classesToLoad;

        // even better, read them from a file and pass the filename to this method
        classesToLoad = new String[]
        {
            "foo.bar.X",
            "foo.bar.Y",
        }

        for(final String className : classesToLoad)
        {
            try
            {
                // load the class
                Class.forName(className);
            }
            catch(final ClassNotFoundException ex)
            {
                // do something that makes sense here
                ex.printStackTrace();
            }
        }
    }
}

Use java -XX:+TraceClassLoading to trace the loading of classes.

Use java -XX:+PrintCompilation to trace when methods are JITed.


The simplest thing to do is ignore the first run. (If that is a valid thing to do) Note: if you run the same code 10,000 times, it will compile the code further and you get better results, so you might want to ignore the first 10K results for some micro-benchmarks.

Some JVMs support eager loading but I don't think Sun's JVM does.

JWrapper support AOT https://www.jwrapper.com/features


Rule #1 for Java benchmarking: The first 15000 times (or so) a method runs aren't interesting.

This thread contains some solid advice: How do I write a correct micro-benchmark in Java?

Tags:

Java