What makes an object immutable, and why are immutable objects safer to share between threads?
An object is immutable when it cannot be changed after it has been made. That means every field is final and there is no way to change the contents of anything the object holds.
public class Main {
public static void main(String[] args) {
Point p = new Point(3, 4);
System.out.println(p);
}
}
And here is an immutable class.
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int x() {
return x;
}
public int y() {
return y;
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
}
And there are three things you have to get right for a class to be truly immutable.
the rule why it matters
-------------------------------- --------------------------------------------
the class is final a subclass could add a setter and
break the promise
every field is final nothing can be changed after the
constructor
the objects the fields hold are a final list can still have things
also immutable added to it
And the third rule is the one that people miss. A field that is final can still point at a list, and a list can still be changed. So a class that holds a list and copies it in the constructor is immutable, and a class that holds a list and keeps the reference that it was given is not.
// This one is immutable. The list is copied and the copy is
// never given away.
public final class Playlist {
private final java.util.List<String> tracks;
public Playlist(java.util.List<String> tracks) {
this.tracks = java.util.List.copyOf(tracks);
}
public java.util.List<String> tracks() {
return tracks;
}
}
And why are immutable objects safer to share between threads? Because a thread cannot change what it does not have a way to change. If nobody can write to the object then two threads reading it at the same time cannot see different values.
the situation what can go wrong
------------------------------- ---------------------------------
a shared object that can change one thread reads it while the other
writes it, and the reader sees half
of an update
a shared object that cannot nothing, because there is no
change write at all
And there is a second benefit that is worth knowing about. An immutable object is safe to publish without any synchronisation at all, because the constructor has finished before any other thread can see the reference. The Java memory model gives you that for free, so there is no need for a volatile field or a lock.
And the third benefit is that an immutable object can be shared as a key in a hash map, and it can be used as a value in a set, and it can be cached, and none of those things need any extra care.
So the rule to remember is this. A final class with final fields that holds only immutable things cannot be changed by anybody, and so nobody can make it inconsistent.
The last question in this topic is about why immutable objects are a safer default.