Skip to main content

Java Concurrency - Immutable

Greetings!

Problem with shared object is any thread can modify it. What if we have an object type which can not be changed? This is where immutable objects come into play.

Immutable object is an object that once created it's state can not be changed.

We can construct an immutable object by protecting the inner state by not sharing any setter method to change inner state.

How to construct an immutable class?


  • Do not provide setter methods.
  • Make all fields final and private.
  • Make the constructor private and use a factory method to create objects.
  • Do not share mutable objects.
  • If mutable objects need to be shared, share a copy.
  • If the constructor accepts external mutable objects as parameters create a copy of them.
  • Make the class final to avoid sub classing.


public final class Counter {
    
    private final int count;
    
    private Counter(int initialCount) {
        this.count = initialCount;
    }
    
    public static Counter newCounter(int initialCount) {
        return new Counter(initialCount);
    }
    
    public int getCount() {
        return this.count;
    }
    
    public Counter add(int value) {
        return new Counter(this.count + value);
    }

}


Java Built-in Immutable Classes

Java standard API includes many immutable classes. Most famous one is String. Below is a list of few of them.

  • String
  • Integer, Long, Float, Double, Boolean, Short, Char, Byte
  • java.math.BigInteger, java.math.BigDecimal
  • java.io.File
  • java.util.UUID


  • Note that assigned variable is not immutable and hence not thread safe. Other threads can replace the constructed object.






Comments