Java concurrency: is final field (initialized in constructor) thread-safe?

后端 未结 9 1084
暖寄归人
暖寄归人 2020-11-29 08:35

Can anyone tell me whether this class is threadsafe or not ?

class Foo {

    private final Map aMap;

    public Foo() {
        aMap =         


        
9条回答
  •  囚心锁ツ
    2020-11-29 09:17

    It's question asked long time ago. However, I have decided to answer the question. First of all, it is totally thread safe code. The reasons are the following.

    1. Its state is well-encapsulated. The class's state consists of map and its key value pairs which are strings which are immutable. So, through encapsulation the class shares its state with other threads in thread-state manner.

    2. Only public method Foo class provides get which publishes immutable objects which are safe for parallel threads because they can't modify published object.

    3. map variable is final which makes it immutable and provides memory visibility.

    To answer the question, it's actually safe initialization. No objects are escaping. Other threads does not see.

提交回复
热议问题