With the arrival of Java 8 we got lambda and streams, and we all start doing "functional programming". One of the properties of functional programing is immutability. To create immutable object in java is not so easy, but it is possible.
Here is the simple example:
public class Test {
public static void main(String []args){
PersonService personService = new PersonService();
Person p = Person.of("XYZ", 12);
Person p2 = personService.setName(p, "New Name");
Person p3 = personService.setAge(p2, 45);
System.out.println(p);
System.out.println(p2);
System.out.println(p3);
}
}
class PersonService {
public Person setName(Person existingPerson, String name) {
return Person.of(name, existingPerson.getAge());
}
public Person setAge(Person existingPerson, int age) {
return Person.of(existingPerson.getName(), age);
}
}
final class Person {
private final String name;
private final int age;
private Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public static Person of(String name, int age) {
return new Person(name, age);
}
public String toString() {
return name + " " + age;
}
}
Many people think garbage collection collects and discards dead objects. In reality, Java garbage collection is doing the opposite! Live objects are tracked and everything else designated garbage. Also Java garbage collection is based on assumption that most objects die young (not referenced anymore shortly after their creation and as such can be destroyed safely). Most developers used to believe that objects creation in Java is slow and that creation of the new objects should be avoided as much as possible. In fact, it does is quite cheap and fast. What is expensive though is an unnecessary creation of long-lived objects which eventually may fill up heap and cause problems.
So is using immutable objects better for GC, because they are not going to live very long ?