Are final static variables thread safe in Java?

前端 未结 8 878
盖世英雄少女心
盖世英雄少女心 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:22

    Initialization of static final fields in a static initialization block is thread safe. However, remember that the object to which a static final reference points may not be thread safe. If the object to which you refer is thread safe (e.g., it's immutable), you're in the clear.

    Each individual HashMap contained in your outer HashMap is not guaranteed to be thread safe unless you use ConcurrentHashMap as suggested in your question. If you do not use a thread-safe inner HashMap implementation, you may get unintended results when two threads access the same inner HashMap. Keep in mind that only some operations on ConcurrentHashMap are synchronized. For example, iteration is not thread-safe.

    0 讨论(0)
  • 2020-12-13 07:25

    the reference to sharedData which is final is thread safe since it can never be changed. The contents of the Map is NOT thread safe because it needs to be either wrapped with preferably a Guava ImmutableMap implementation or java.util.Collections.unmodifiableMap() or use one of the Map implementations in the java.util.concurrent package.

    Only if you do BOTH will you have comprehensive thread safety on the Map. Any contained Maps need to be immutable or one of the concurrent implementations as well.

    .clone() is fundamentally broken, stay away

    cloning by default is a shallow clone, it will just return references to container objects not complete copies. It is well documented in generally available information on why.

    0 讨论(0)
提交回复
热议问题