Reputation: 87
I have come across eager loading in Java in two classes of Spring NestedRuntimeException
and AbstractApplicationContext
, both of these cases resolve the same Class loader issue using static code block, but the way they are used is confusing.
The confusion is regarding the call to ClassName.class.getName()
in static code block, how does this resolve class loader issue.
static {
// Eagerly load the ContextClosedEvent class to avoid weird classloader issues
// on application shutdown in WebLogic 8.1. (Reported by Dustin Woods.)
ContextClosedEvent.class.getName();
}
If I were to do this same, I would get the class loader and load this class manually
Thread.currentThread()
.getContextClassLoader().loadClass(ContextClosedEvent.class.getName());
Any expert advice will be appreciated.
Upvotes: 4
Views: 1184
Reputation: 356
In the first case, as bellow example, ContextClosedEvent
will be loaded as soon as YourClass
is used.
class YourClass {
static {
// Eagerly load the ContextClosedEvent class to avoid weird classloader issues
// on application shutdown in WebLogic 8.1. (Reported by Dustin Woods.)
ContextClosedEvent.class.getName();
}
}
The second case, ContextClosedEvent
will be loaded when your code is running, the loadClass
method will be invoked 2 times. The first time is for ContextClosedEvent.class
reference (invoked by JVM), the second time is your manual call.
The first time, ContextClosedEvent
is actually loaded from class path. The second time, it depends on your ContextClassLoader
. By default, JVM's class loader will findLoadedClass
instead of load the class again.
As bellow example, loadClass
method will be called twice when main
method running.
class Main {
public static void main(String[] args) throws ClassNotFoundException {
Thread.currentThread()
.getContextClassLoader().loadClass(ContextClosedEvent.class.getName());
}
}
To see how static block works, run this example
class Main {
public static void main(String[] args) {
System.out.println("main method invoked");
}
static {
System.out.println("static block invoked");
}
}
Upvotes: 4