What is Immutable Class. Why would you choose it? How would you make a class immutable?

Carvia Tech | May 19, 2019 | 2 min read | 284 views | Multithreading and Concurrency


When the state of object can not be changed after its construction then the object is called Immutable.

Benefits of Immutable Objects

Inherent thread-safety

Immutable objects are inherently thread-safe, thus help writing multi-threading code without much worries.

Cacheability

Because Immutable objects do not change their value, we can freely cache them and be confident that their value won’t change.

Good candidate for Hashing Keys

Immutable objects are good candidate for hash keys because their hashcode can be cached and reused for better performance. They make the best HashMap keys.

Easy to understand

Immutable classes are easy to understand, as they possess a single state, which is controlled by their constructor.

Which Objects should be made Immutable

Immutable classes are ideal for representing ADT’s (Abstract Data Type) value.

All classes should be designed to be immutable unless there is a specific reason not to do so.

— Joshua Bloch

Guidelines for Making a class Immutable

  1. All fields should be declared final

  2. Class itself is declared final so that the derived classes do not make it Mutable.

  3. this reference should not be allowed to escape during object construction such as in anonymous inner classes (for example adding action listener)

  4. Any field that contains reference to mutable objects (such as arrays, collections, StringBuffer, etc)

    • Are private

    • Are never returned or exposed to the caller

    • Are the only reference to the Objects that they refer

    • Do not change the state of the referenced object after the construction.

    • If mutable fields must be returned to the caller, then a defensive copy should be returned so that the changes do not reflect in the inner data structure.
      For example,

      Defensive copy of mutable object
      public List getList() {
           return Collections.unmodifiableList(list); (1)
      }
      1 defensive copy of the mutable field before returning it to caller
    • If a mutable Object is passed in the constructor (like an array), then Immutable class should first make a defensive copy of the mutable object before storing its reference.

You can refer to other post where we will see how to create immutable class that has mutable member variable


Multithreading and Concurrency:
  1. Top 20 Java Concurrency Interview Questions and Answers
  2. What is ThreadLocal in Java, where will you use this class
  3. What do you understand by Java Memory Model?
  4. How will you handle ConcurrentModificationException in Java
  5. What is AtomicInteger class and how it works internally
  6. Discuss internals of a ConcurrentHashmap (CHM) in Java
  7. Can the keys in HashMap be mutable
See all articles in Multithreading and Concurrency
Top articles in this category:
  1. Design an Immutable class that has an java.util.Date member
  2. What is ThreadLocal in Java, where will you use this class
  3. Given a collection of 1 million integers, All ranging between 1 to 9, how would you sort them in Big O(n) time
  4. What is AtomicInteger class and how it works internally
  5. How will you implement your custom threadsafe Semaphore in Java
  6. what are Key classes in java.util.concurrent package
  7. What is Deadlock in Java? How to troubleshoot and how to avoid deadlock



Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info