Why Caches with Immutable Classes?
Why do immutable classes have some kind of cache associated with them?
--
Have you ever wondered about the implications of careless designs of Immutable classes and why the immutable classes have an associated cache? Read this article till the end and take your knowledge a little up about immutable classes. And also know about the reasons behind the flyweight design pattern.
In these two articles(this, this), we mentioned the strict rules for designing the immutable classes. But we missed one very important point that we need to be careful about — Java’s heap contamination. The main disadvantage of immutable classes in Java is that they contaminate the heap memory.
How?
Well, for example, take the Student
class from one of the previous articles.
final class Student {
private final int id;
private final String name;
private final int deptNo;
public Student(int id, String name, int deptNo) {
this.id = id;
this.name = name;
this.deptNo = deptNo;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getDeptNo() {
return deptNo;
}
}
Clearly, the above class is an immutable class because it follows all the guidelines. Let us say we have a Student
object as below.
Student std10 = new Student(10, "JACK", 1001);
Now we want to create another student having the same name and belonging to the same department. We can create another student object as below.
Student std11 = new Student(11, "JACK", 1001);
But we can also implement it in a nicer way and the conventional way that every immutable class follows. We can implement some instance methods that take a corresponding field and return a new Student
object. Such as below.
public Student withId(int id) {
return new Student(id, this.name, this.deptNo);
}
public Student withName(String name) {
return new Student(this.id, name, this.deptNo);
}
public Student withDeptNo(String deptNo) {
return new Student(this.id, this.name, deptNo);
}