Must all properties of an immutable object be final?

12,783

Solution 1

The main difference between an immutable object (all properties final) and an effectively immutable object (properties aren't final but can't be changed) is safe publication.

You can safely publish an immutable object in a multi threaded context without having to worry about adding synchronization, thanks to the guarantees provided by the Java Memory Model for final fields:

final fields also allow programmers to implement thread-safe immutable objects without synchronization. A thread-safe immutable object is seen as immutable by all threads, even if a data race is used to pass references to the immutable object between threads. This can provide safety guarantees against misuse of an immutable class by incorrect or malicious code. final fields must be used correctly to provide a guarantee of immutability.

As a side note, it also enables to enforce immutability (if you try to mutate those fields in a future version of your class because you have forgotten it should be immutable, it won't compile).


Clarifications

  • Making all the fields of an object final does not make it immutable - you also need to make sure that (i) its state can't change (for example, if the object contains a final List, no mutating operations (add, remove...) must be done after construction) and (ii) you don't let this escape during construction
  • An effectively immutable object is thread safe once it has been safely published
  • Example of unsafe publication:

    class EffectivelyImmutable {
        static EffectivelyImmutable unsafe;
        private int i;
        public EffectivelyImmutable (int i) { this.i = i; }
        public int get() { return i; }
    }
    
    // in some thread
    EffectivelyImmutable.unsafe = new EffectivelyImmutable(1);
    
    //in some other thread
    if (EffectivelyImmutable.unsafe != null
        && EffectivelyImmutable.unsafe.get() != 1)
        System.out.println("What???");
    

    This program could in theory print What???. If i were final, that would not be a legal outcome.

Solution 2

You can easily guarantee immutability by encapsulation alone, so it's not necessary:

// This is trivially immutable.
public class Foo {
    private String bar;
    public Foo(String bar) {
        this.bar = bar;
    }
    public String getBar() {
        return bar;
    }
}

However, you also must guarantee it by encapsulation in some cases, so it's not sufficient:

public class Womble {
    private final List<String> cabbages;
    public Womble(List<String> cabbages) {
        this.cabbages = cabbages;
    }
    public List<String> getCabbages() {
        return cabbages;
    }
}
// ...
Womble w = new Womble(...);
// This might count as mutation in your design. (Or it might not.)
w.getCabbages().add("cabbage"); 

It's not a bad idea to do so to catch some trivial errors, and to demonstrate your intent clearly, but "all fields are final" and "the class is immutable" are not equivalent statements.

Solution 3

Immutable = not changeable. So making properties final is a good idea. If not all properties of an object are protected from being changed I wouldn't say the object is immutable.

BUT an object is also immutable if it doesn't provide any setters for it's private properties.

Solution 4

Immutable objects MUST not be modified in any way after their creation. final of course helps to achieve that. You guarantee that they will not ever be changed. BUT what if you have an array inside your object that is final? Of course the reference is not changable, but the elements are. Look here at almost the same question I gave also:

Link

Solution 5

No.

For example, see the implementation of java.lang.String. Strings are immutable in Java, but the field hash is not final (it is lazily computed the first time hashCode is called and then cached). But this works because hash can take on only one nondefault value that is the same every time it is computed.

Share:
12,783
DRastislav
Author by

DRastislav

Student

Updated on June 02, 2022

Comments

  • DRastislav
    DRastislav almost 2 years

    Must immutable objects have all properties be final?

    According to me not. But I don't know, whether I am right.

  • Eugene
    Eugene about 11 years
    while I do agree with u, what about an object that has an array field that is final? The reference is immutable, but the values are not. Same thing about ImmutableList of StringBuilders for example. Are these objects considered thread-safe?
  • NimChimpsky
    NimChimpsky about 11 years
    how will an object with non final private fields (initialized on object construction) ever be thread unsafe ?
  • assylias
    assylias about 11 years
    If all their fields are final they can still be safely published but it is not enough to make them thead safe.
  • NimChimpsky
    NimChimpsky about 11 years
    In what situation would they be thread unsafe ? Nothing can change after object creation ... so I don't undestand how they would ever be unsafe.
  • assylias
    assylias about 11 years
    @NimChimpsky I have clarified how an effectively immutable object could cause thread safety issues.
  • supercat
    supercat over 10 years
    If an immutable class uses an array to encapsulate a sequence of values, how should it ensure that writes to array elements will be visible before the class gets exposed to outside code?
  • Amar Magar
    Amar Magar over 8 years
    i have a question: how we can achieve functionality like string class for ex. in case of string class String firstname = new String("amar"); String name ="amar"; so both firstname and name will point to the same memory location on stack please help
  • amarnath harish
    amarnath harish over 5 years
    in the first case someone can extend the class and change subclass's state and assign to parent class reference thus changing state.
  • Montre
    Montre over 5 years
    Yes, but it depends on the context if you think the rogue subclasser is a likely scenario. Declaring a class as final or adhering to the open-closed principle in code review would address that. That said the child class cannot change the value of bar in any case legitimately, so Foo as declared is immutable, and I have a hunch will appear so to all clients of such an object through the interface exposed by Foo.
  • Montre
    Montre over 5 years
    Actually this might even adhere to the OCP. It’s not great design but in effect it’s as if you bundled two independent objects, one mutable and one not, under one reference
  • Adrien Brunelat
    Adrien Brunelat over 3 years
    I don't really understand the last example you give. Could you elaborate that part? I understand the first statement but not the second one. How would final make it illegal?
  • assylias
    assylias over 3 years
    @AdrienBrunelat in the example, there is a data race and there is no guarantee that a non null object will be fully constructed (i.e. a field could still be uninitialised). If the fields are final, the JLS guarantees that they will be initialised even if the object is accessed via a data race (cf. the quote in my answer).