When gets the static initializer of a private static class exectuted?

J

joes

Hello Gurus

I have a question. I have a class which holds an inner class declared
"private static". This inner class has a static field which is
immediately initilaized. When gets this static initilaziation of a
private static class exectuted?

- does it get executed when the outer class is loaded?
- does it get only executed if the inner class is getting loaded?


Example:
------------
public class Log {


private static class LoggerHolder {
public static Logger sLogger =
LoggerHelper.getLogger(LOGGER_CLASS);
}

public static Logger getLogger() {
return LoggerHolder.sLogger;
}
}

many thanks
regards

Mark
 
M

Mike Schilling

joes said:
Hello Gurus

I have a question. I have a class which holds an inner class
declared
"private static". This inner class

Nitpick. It's not an inner class. Inner classes may not have static
fields. It's a "nested" class.
has a static field which is
immediately initilaized. When gets this static initilaziation of a
private static class exectuted?

- does it get executed when the outer class is loaded?
- does it get only executed if the inner class is getting loaded?

Only when the class which defines the static field gets loaded.
 
R

Roedy Green

- does it get executed when the outer class is loaded?
- does it get only executed if the inner class is getting loaded?

Insert System.out.println( "inner(outer) static loading")
and tell us what you discover.
 
L

Lew

Mike said:
Nitpick. It's not an inner class. Inner classes may not have static
fields. It's a "nested" class.
Only when the class which defines the static field gets loaded.

Only when the first object of the nested class type is used. This is the
basis for a thread-safe lazy-loading idiom much ballyhooed by Brian Goetz, et al.
private static class LazySomethingHolder {
public static Something something = new Something();
}

...

public static Something getInstance() {
return LazySomethingHolder.something;
}

The nested class's static initializer is not run when the outer class is
loaded but when the getInstance() method is first called.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top