Immutable objects are thread safe, but why?

后端 未结 6 1014
后悔当初
后悔当初 2020-11-29 08:11

Lets say for example, a thread is creating and populating the reference variable of an immutable class by creating its object and another thread kicks in before the first on

6条回答
  •  时光取名叫无心
    2020-11-29 08:38

    Immutable objects are thread safe, but why?

    An immutable object is an object that is no longer modified once it has been constructed. If in addition, the immutable object is only made accessible to other thread after it has been constructed, and this is done using proper synchronization, all threads will see the same valid state of the object.

    If one thread is creating populating the reference variable of the immutable class by creating its object and at the second time the other thread kicks in before the first thread completes and creates another object of the immutable class, won't the immutable class usage be thread unsafe?

    No. What makes you think so? An object's thread safety is completely unaffected by what you do to other objects of the same class.

    Are they trying to say that the other thread may re-point the reference variable to some other object of the immutable class and that way the threads will be pointing to different objects leaving the state inconsistent?

    They are trying to say that whenever you pass something from one thread to another, even if it is just a reference to an immutable object, you need to synchronize the threads. (For instance, if you pass the reference from one thread to another by storing it in an object or a static field, that object or field is accessed by several threads, and must be thread-safe)

提交回复
热议问题