简体   繁体   中英

Why static final variable use static method initialization need synchronized?

In Jetty source code, the jetty-xml module, XmlConfiguration has the following code:

java private static final XmlParser __parser = initParser();

private synchronized static XmlParser initParser() {
XmlParser parser = new XmlParser();
URL config60 = Loader.getResource(XmlConfiguration.class, "org/eclipse/jetty/xml/configure_6_0.dtd");
URL config76 = Loader.getResource(XmlConfiguration.class, "org/eclipse/jetty/xml/configure_7_6.dtd");
URL config90 = Loader.getResource(XmlConfiguration.class, "org/eclipse/jetty/xml/configure_9_0.dtd");

parser.redirectEntity("configure.dtd", config90);
parser.redirectEntity("configure_1_0.dtd", config60);
parser.redirectEntity("configure_1_1.dtd", config60);

...

return parser;

the __parser variable use the static method initParser() initialization.the __parser should be thread-safe,only load once by the classloader, why the initParser() need to use synchronized ? Whether excess?

Further explanations:I debug the Jetty source code, from the jetty-start module, then invoke the jetty-xml module.

I don't think it needs to be synchronized at all.

The Java Language Specification guarantees that Java class initialization (ie the initialization of the classes static s, etcetera) is performed within a lock to prevent race conditions. This applies whether the class is loaded once, or many times (ie by different class loaders).

I suspect that the author of this code was simply not aware of how the JVM handles this, and is taking unnecessary precautions.

(On the other hand, these "belt and braces" precautions are harmless, and the performance impact is trivial: probably unmeasurable.)


For the record, the procedure for class initialization is specified in the JLS in Section 12.4.2 .

If you make sure that there is at most one class loader then there is no need for synchronization. The static initialization code is run once per class loader.

From what i can see in the Jetty WebAppContext only one class loader can be set in configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM