Immutable objects are thread safe, but why?

后端 未结 6 1015
后悔当初
后悔当初 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:51

    Actually immutable objects are always thread-safe, but its references may not be.

    Confused?? you shouldn't be:-

    Going back to basic: Thread-safe simply means that two or more threads must work in coordination on the shared resource or object. They shouldn't over-ride the changes done by any other thread.

    Now String is an immutable class, whenever a thread tries to change it, it simply end up creating a new object. So simply even the same thread can't make any changes to the original object & talking about the other thread would be like going to Sun but the catch here is that generally we use the same old reference to point that newly created object.

    When we do code, we evaluate any change in object with the reference only.

    Statement 1: String str = "123"; // initially string shared to two threads

    Statement 2: str = str+"FirstThread"; // to be executed by thread one

    Statement 3: str=str+"SecondThread"; // to be executed by thread two

    Now since there is no synchronize, volatile or final keywords to tell compiler to skip using its intelligence for optimization (any reordering or caching things), this code can be run in following manner.

    1. Load Statement2, so str = "123"+"FirstThread"
    2. Load Statement3, so str = "123"+"SecondThread"
    3. Store Statement3, so str = "123SecondThread"
    4. Store Statement2, so str = "123FirstThread"

    and finally the value in reference str="123FirstThread" and for sometime if we assume that luckily our GC thread is sleeping, that our immutable objects still exist untouched in our string pool.

    So, Immutable objects are always thread-safe, but their references may not be. To make their references thread-safe, we may need to access them from synchronized blocks/methods.

提交回复
热议问题