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

Carvia Tech | May 19, 2019 | 2 min read | 213 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. Removing elements while iterating over a Java Collection
  2. Discuss internals of a ConcurrentHashmap (CHM) in Java
  3. What is difference between sleep() and wait() method in Java?
  4. What will happen if we don't synchronize getters/accessors of a shared mutable object in multi-threaded applications
  5. Design an Immutable class that has an java.util.Date member
  6. What is ThreadLocal in Java, where will you use this class
  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. What is AtomicInteger class and how it works internally
  4. Given a collection of 1 million integers, All ranging between 1 to 9, how would you sort them in Big O(n) time
  5. what are Key classes in java.util.concurrent package
  6. How will you implement your custom threadsafe Semaphore in Java
  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 month ago


Recommended books for interview preparation:

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