Are final static variables thread safe in Java?

前端 未结 8 897
盖世英雄少女心
盖世英雄少女心 2020-12-13 06:40

I\'ve read around quite a bit but haven\'t found a definitive answer.

I have a class that looks like this:

    public class Foo() {

        private          


        
8条回答
  •  清歌不尽
    2020-12-13 07:19

    Yes, this is thread safe too. All final members of your static class will be initialized before any thread is allowed to access them.

    If the static block fails during initialization, an ExceptionInInitializerError will be raised in the thread that first attempts initialization. Subsequent attempt to reference the class will raise a NoClassDefFoundError.

    In general, the contents of a HashMap have no guarantee of visibility across threads. However, the class initialization code uses a synchronized block to prevent multiple threads from initializing the class. This synchronization will flush the state of the map (and the HashMap instances that it contains) so that they will be correctly visible to all threads—assuming that no changes are made to the map, or the maps it contains, outside the class initializer.

    See the Java Language Specification, §12.4.2 for information about class initialization and the requirement for synchronization.

提交回复
热议问题