Reputation: 3803
Okay, so say I have a class that looks like this :
public class SignupServlet extends HttpServlet {
private static final Logger SERVLET_LOGGER=COMPANYLog.open(SignupServlet.class);
private static final ExceptionMessageHandler handler = new ExceptionMessageHandler();
private static final SignupServletObservableAgent signupObservableAgent =
new SignupServletObservableAgent(null, SERVLET_LOGGER);
}
Can I count on the class loader to initialize those fields in order, such that I can rely on SERVLET_LOGGER to be instantiated before signupObservableAgent?
Upvotes: 38
Views: 20357
Reputation: 143064
Yes, they are initialized in the order in which they appear in the source. You can read all of the gory details in The Java Language Specification, §12.4.2. See step 9, which reads:
Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
Upvotes: 59
Reputation: 327
This is a place where you can use a static block which would guarantee the sequence of execution.
public class SignupServlet extends HttpServlet {
private static final Logger SERVLET_LOGGER;
private static final ExceptionMessageHandler handler;
private static final SignupServletObservableAgent signupObservableAgent;
static {
SERVLET_LOGGER = COMPANYLog.open(SignupServlet.class);
handler = new ExceptionMessageHandler();
signupObservableAgent = new SignupServletObservableAgent(null, SERVLET_LOGGER);
}
}
Upvotes: -2
Reputation: 21
if sub class and super class is there.
Upvotes: 1
Reputation: 7038
I think that initialization of static fields could be re-ordered. At least that is how I understand JMM specification
There are a number of cases in which accesses to program variables (object instance fields, class static fields, and array elements) may appear to execute in a different order than was specified by the program.
Upvotes: 2