My understanding of class loading was that a class is loaded when it is needed first (to make it very simple). Running the following sample with the -verbose: class and a modified version of the Iterators class that prints a message when its clinic is called, I noticed something that I canβt explain, though:
public class IteratorsTest { public static void main(String[] args) { com.google.common.collect.Iterators.forArray(1, 2, 3); } }
The output (cleared) is as follows:
[Loaded com.google.common.collect.Iterators from file:...] [Loaded com.google.common.collect.Iterators$1 from file:...] ---------> Iterators <clinit>
Why are $ 1 iterators loaded before the clinic call? It is determined only in the clinic, right?
static final UnmodifiableListIterator<Object> EMPTY_LIST_ITERATOR = new UnmodifiableListIterator<Object>() { ... }
The result is the following byte code:
static <clinit>()V L0 GETSTATIC java/lang/System.out : Ljava/io/PrintStream; LDC "---------> Iterators clinit --------------"** INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V L1 NEW com/google/common/collect/Iterators$1 DUP INVOKESPECIAL com/google/common/collect/Iterators$1.<init> ()V L2 PUTSTATIC com/google/common/collect/Iterators.EMPTY_LIST_ITERATOR : Lcom/google/common/collect/UnmodifiableListIterator;
And to confuse me even more, I have another sample (too complicated to post here), where the same line of code, as basically the above, leads to the following output:
[Loaded com.google.common.collect.Iterators from file:...] ---------> Iterators <clinit> [Loaded com.google.common.collect.Iterators$1 from file:...]
This is actually what I expected from a simple test program.
I tried to find the answer here https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html , but that really didn't help.
- What could be the reason that sometimes the clinician is executed first, and sometimes the anonymous class is loaded first?
- Is there a way to keep track of when the JVM causes class climate? something like -verbose: class or -XX: + TraceClassLoading etc.?