Reputation: 848
We have an application in Java that has a Utilities class that has a bunch of static methods and members. One of them gets initialised by creating another class and call it's method
private static final Set<Class<? extends AbstractEntity>> ABSTRACT_ENTITIES = new Reflections("something").getSubTypesOf(AbstractEntity.class);
Correct me if I am wrong but they way Java treats static members is that they will get initialised once in the beggining (I don't remember if this is in the initialisation of the application or the first time the class gets referenced).
My question if what happens if the initialisation of the member I mentioned throws an exception?
I have noticed this in the profiler when one of the static methods gets called. The method doesn't use this particular member.
I didn't notice any misbehaviour (but it's a big system and I am new) but the exception seems to have been thrown hundreds of time in 20mins of operation locally with my only doing some very basic things.
My first assumption is that while an exception is thrown that does not get handled the static method continues and executes and then next time a method from the class gets called the same thing happens. The member tries to initialise, thrown as exception and so on.
Am I correct that this is what might be happening with static member not being initialised because of an exception?
Upvotes: 0
Views: 46
Reputation: 2386
static final variables are initialized during classloading (once per ClassLoader). If an Exception occurs during the initialization, the classloading will fail.
Example:
package test;
import java.util.Optional;
public class SomeClass {
private static final Object SOME_VARIABLE = Optional.empty().orElseThrow(RuntimeException::new);
public static void main(String[] args) {
}
}
Causes:
java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException
at java.util.Optional.orElseThrow(Optional.java:290)
at test.SomeClass.<clinit>(SomeClass.java:7)
Exception in thread "main"
And:
package test;
public class SomeClass {
private static final Object SOME_VARIABLE = new SomeClass();
public static void main(String[] args) {
Object a = SomeClass.SOME_VARIABLE;
Object b = SomeClass.SOME_VARIABLE;
if (a == b) {
System.out.println("same instance");
}
}
}
Produces:
same instance
Upvotes: 1