Program to create immutable (thread safe) class in java (example)

1. What is immutable class?

  • The class whose state does not change after its construction is called immutable class.
  • There are various immutable classes in java like String, Integer, Long, Double (or all wrapper classes).

2. Example of immutable class in java i.e. String class

	String IAmImmutable = "I am immutable class";
	String newString = IAmImmutable.substring(IAmImmutable.length() / 2);
	String anotherNewString = IAmImmutable.concat(newString);
	String yetNewString = IAmImmutable.replace('c', 'C');

We have shown some (and no method changes the state of String instance) of the methods of String class, We have seen the “IAmImmutable” instance never got changed after its creation, whenever there is any change in IAmImmutable instance, the new instance of String is created. hence maintaining the immutability of String class.

3. How can we create immutable (thread safe) class in java ?

  • In java we have final keyword, which can be used with variable, class, method to signify their final state.
  • We will see that final keyword comes in our rescue while creating an immutable class in java.

3.1 How the state of object can be changed?

  • Whenever there is changes in data member(s) of object, its state got changed, If we can protect the data members of class from modification, its state can be preserved.
  • We just have to block the ways, via which, the state of an object will be changed.

3.2 Advantage of immutable class:

With immutability, we are not worried about thread safety as their state will never. Immutable classes become thread safe automatically. Also, we have will observe the immutable classes like String are getting used (as keys) in collections framework (Due to same reason that their state does not change).

3.3 Create immutable class in java ?

  1. The class should not have any setter method.
  2. All data members should be final and private.
  3. Mark the class as final so that nobody can override its methods.
  4. Do not return references of mutable fields (So that nobody will change the state from outside).

4. Program to create immutable (thread safe) class in java (example)

package org.learn;

public final class Employee {

	private final String name;
	private final int age;
	private final String gender;

	public Employee(final String name, final int age, final String gender) {
		this.name = name;
		this.age = age;
		this.gender = gender;
	}

	public String toString() {
		return "[" + name + " " + age + " " + gender + "]";
	}

	public String getName() {
		return name;
	}

	public int getAge() {
		return age;
	}

	public String getGender() {
		return gender;
	}
	
	public static void main(String[] args) {
		Employee employee = new Employee("Richard", 25, "Male");
		System.out.println(employee);
	}
}

Output – immutable Employee class in java (example)

[Richard 25 Male]
Scroll to Top