What are the benefits of immutable objects in Java?

Interview question: What are the benefits of immutable objects in Java?

The answer:

Basic Answer

1. Immutable objects are thread-safe.

2. As a result of being thread-safe immutability makes it easier to parallelize a program across multiple threads.

3. You can safely cache references to immutable objects since their state cannot change.

Further Explanation

The biggest benefit of creating immutable objects is that you know they will be thread-safe. Their state cannot be changed once created. Examples of immutable objects in Java are the String object, and the primitive wrapper objects such as Integer, Double, Short, Long, Boolean, and Byte. When working with thread-safe objects, you can parallelize your program so that multiple threads can safely use these objects. It is also possible to cache these objects similar to how Java caches, by default, Integer objects from -128 to 127 by utilizing a Flyweight pattern.

How to Create Immutable Objects

It isn’t terribly difficult to create immutable objects in Java. Here are the steps involved:

1. Mark the class as final.

2. All data field types should be immutable themselves and marked private and final.

3. Do not include any setter methods. All data must be set at the time of object creation in the constructor.

4. Do not allow any method of the class to change the state.

Other Helpful Tips

1. Wrap all Java Collections in newly instantiated immutable variant. You can find the utility methods in the Collections class.