Different between immutable and effectively immutable objects?

后端 未结 4 918
粉色の甜心
粉色の甜心 2021-02-04 02:23

This is a sentence from Java Concurrency in Practice

Shared read-only objects include immutable and effectively immutable objects.

4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 03:01

    Immutable objects completely encapsulates their internal state and they do not allow modification of that state after construction (possibly with the use of final, etc) therefore they are safe to share between multiple threads because reading from a shared object is not harmful from multiple threads.

    Effectively immutable objects may change their state prior to being shared between multiple threads, but after they are "published" (ie multiple references are given to several threads) they protect themselves from modification.

    Immutable objects prevent you from using useful software engineering practices like lazy initialization because in order to lazy init a property or field they have to be mutable violating the carefree concurrency sharing property of them. Effectively immutable objects relax these constraints to get a best of both worlds approach by carefully knowing when they can safely modify their internal state and when it is forbidden.

提交回复
热议问题