Immutable objects are thread safe, but why?

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

    Immutability doesn't imply thread safety.In the sense, the reference to an immutable object can be altered, even after it is created.

    //No setters provided
    class ImmutableValue
    {
    
         private final int value = 0;
    
         public ImmutableValue(int value)
         {
              this.value = value;
         }
    
         public int getValue()
         {
              return value;
         }
    }
    
    public class ImmutableValueUser{
      private ImmutableValue currentValue = null;//currentValue reference can be changed even after the referred underlying ImmutableValue object has been constructed.
    
      public ImmutableValue getValue(){
        return currentValue;
      }
    
      public void setValue(ImmutableValue newValue){
        this.currentValue = newValue;
      }
    
    }
    

提交回复
热议问题