Monday, March 4, 2013

How to create Immutable Class and Object in Java - Tutorial Example

Writing or creating immutable classes in Java is becoming popular day by day, because of concurrency and multithreading advantage provided by immutable objects. Immutable objects offers several benefits over conventional mutable object, especially while creating concurrent Java application. Immutable object not only guarantees safe publication of object’s state, but also can be shared among other threads without any external synchronization. In fact JDK itself contains several immutable classes like String, Integer and other wrapper classes. For those, who doesn’t know what is immutable class or object, Immutable objects are those, whose state can not be changed once created e.g. java.lang.String, once created can not be modified e.g. trim, uppercase, lowercase. All modification in String result in new object, see why String is immutable in Java for more details. In this Java programming tutorial, we will learn, how to write immutable class in Java or how to make a class immutable. By the way making a class immutable is not difficult on code level, but its the decision to make, which class mutable or immutable which makes difference. I also suggest reading, Java Concurrency in Practice to learn more about concurrency benefit offered by Immutable object.

What is immutable class in Java

What is Immutable class and object, how to create Immutable in Java with exampleAs said earlier, Immutable classes are those class, whose object can not be modified once created, it means any modification on immutable object will result in another immutable object. best example to understand immutable and mutable objects are, String and StringBuffer. Since String is immutable class, any change on existing string object will result in another string e.g. replacing a character into String, creating substring from String, all result in a new objects. While in case of mutable object like StringBuffer, any modification is done on object itself and no new objects are created. Some times this immutability of String can also cause security hole, and that the reason why password should be stored on char array instead of String.


How to write immutable class in Java

Despite of few disadvantages, Immutable object still offers several benefits in multi-threaded programming and it’s a great choice to achieve thread safety in Java code. here are few rules, which helps to make a class immutable in Java :

1. State of immutable object can not be modified after construction, any modification should result in new immutable object.
2. All fields of Immutable class should be final.
3. Object must be properly constructed i.e. object reference must not leak during construction process.
4. Object should be final in order to restrict sub-class for altering immutability of parent class.

By the way, you can still create immutable object by violating few rules, like String has its hashcode in non final field, but its always guaranteed to be same. No matter how many times you calculate it, because it’s calculated from final fields, which is guaranteed to be same. This required a deep knowledge of Java memory model, and can create subtle race conditions if not addressed properly. In next section we will see simple example of writing immutable class in Java. By the way, if your Immutable class has lots of optional and mandatory fields, then you can also use Builder design pattern to make a class Immutable in Java.

Immutable Class Example in Java

Here is complete code example of writing immutable class in Java. We have followed simplest approach and all rules for making a class immutable, including it making class final to avoid putting immutability at risk due to Inheritance and Polymorphism.

public final class Contacts {

    private final String name;
    private final String mobile;

    public Contacts(String name, String mobile) {
        this.name = name;
        this.mobile = mobile;
    }
  
    public String getName(){
        return name;
    }
  
    public String getMobile(){
        return mobile;
    }
}

This Java class is immutable, because its state can not be changed once created. You can see that all of it’s fields are final. This is one of the most simple way of creating immutable class in Java, where all fields of class also remains immutable like String in above case. Some time you may need to write immutable class which includes mutable classes like java.util.Date, despite storing Date into final field it can be modified internally, if internal date is returned to the client. In order to preserve immutability in such cases, its advised to return copy of original object, which is also one of the Java best practice. here is another example of making a class immutable in Java, which includes mutable member variable.

public final class ImmutableReminder{
    private final Date remindingDate;
  
    public ImmutableReminder (Date remindingDate) {
        if(remindingDate.getTime() < System.currentTimeMillis()){
            throw new IllegalArgumentException("Can not set reminder” +
                        “ for past time: " + remindingDate);
        }
        this.remindingDate = new Date(remindingDate.getTime());
    }
  
    public Date getRemindingDate() {
        return (Date) remindingDate.clone();
    }
}

In above example of creating immutable class, Date is a mutable object. If getRemindingDate() returns actual Date object than despite remindingDate being final variable, internals of Date can be modified by client code. By returning clone() or copy of remindingDate, we avoid that danger and preserves immutability of class.

Benefits of Immutable Classes in Java

As I said earlier Immutable classes offers several benefits, here are few to mention:

1) Immutable objects are by default thread safe, can be shared without synchronization in concurrent environment.
2) Immutable object simplifies development, because its easier to share between multiple threads without external synchronization.

3) Immutable object boost performance of Java application by reducing synchronization in code.

4) Another important benefit of Immutable objects is reusability, you can cache Immutable object and reuse them, much like String literals and Integers.  You can use static factory methods to provide methods like valueOf(), which can return an existing Immutable object from cache, instead of creating a new one.

Apart from above advantages, immutable object has disadvantage of creating garbage as well. Since immutable object can not be reused and they are just a use and throw. String being a prime example, which can create lot of garbage and can potentially slow down application due to heavy garbage collection, but again that's extreme case and if used properly Immutable object adds lot of value.

That's all on how to write immutable class in Java. we have seen rules of writing immutable classes, benefits offered by immutable objects and how we can create immutable class in Java which involves mutable fields. Don’t forget to read more about concurrency benefit offered by Immutable object in one of the best Java book recommended to Java programmers, Concurrency Practice in Java.


Related Java programming concepts and tutorials

23 comments :

SARAL SAXENA said...

Hi Javin,
Nice article , Just want to add few more things..

1) All the fields must be private and preferably final
2) Ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
3) Fields must be populated from the Constructor/Factory
4) Don't provide any setters for the fields
5) Watch out for collections. Use Collections.unmodifiable*. Also, collections should contain only immutable Objects
6) All the getters must provide immutable objects or use defensive copying
7) Don't provide any methods that change the internal state of the Object

Guys please also refer to this url.. http://www.javaranch.com/journal/2003/04/immutable.htm

Raj said...

Hi Javin,

Thanks for posting such very useful posts.

It would have been very very useful if the site consists a search option to check for a particular topic in specific.

SARAL SAXENA said...

One more thing that I would like to add Javin regarding the example shown that is..

we should make a copy of remindingDate.getTime() BEFORE checking it against your class invariants. Otherwise an attacker with a reference(long time = remindingDate.getTime();) to your remindingDate could call a .set method on it to change the value after you've checked it's validity.The program should be like ...

public final class ImmutableReminder{
private final Date remindingDate;

public ImmutableReminder (Date remindingDate) {
long incomingTime = remindingDate.getTime()

if(incomingTime < System.currentTimeMillis()){
throw new IllegalArgumentException("Can not set reminder” +
“ for past time: " + remindingDate);
}
this.remindingDate = new Date(incomingTime);
}

public Date getRemindingDate() {
return (Date) remindingDate.clone();
}
}

Javin @ Use valueof to convert String to int said...

@Saral, Once again great comment. Your point is perfectly valid while using mutable class like Date here, This once again highlight, importance of Immutable classes for security reasons as well.

SARAL SAXENA said...

Thanks Javin..One must think before making an class as immutable as we know..

1) With immutability, any time you need to modify data, you need to create a new object. This can be expensive.

2)Reflection based frameworks are complicated by immutable objects since they requires constructor injection

3)constructor argument names are not usually available through reflection, which forces us to depend on argument order for dependency resolution

John said...

How do you decide to make a class Immutable in Java? I understand about value classes like String, Integer, but again How about java.util.Date, should that's a value class, should it should be immutable. Why Java designer keeps java.util.Date mutable, please advise.

John said...

@Raj, there is Google search text box in top right. Did you try that?

Shruti said...

Over the year, I learned that value object, which is usually domain specific must be immutable. Class es like Order, Trade, Customer, Product are couple of examples of value Object. Interestingly you should be having corresponding database table for them and each row is equal to one instance of value object.

Jo said...

Is making field final is necessary to create Immutable class? I guess when you make your class final, it means no one can sub class, which means no overriding of methods. Also if you don't provide setter than no one can modify state of object. What is the point of making member variable final inside Immutable class?

Anonymous said...

BigDecimal and BigInteger are also good example of Immutable classes from JDK.

Graham Allan said...

Hi,

You and your readers may be interested in an open source tool I created which allows you to test if your class is immutable or not. For example, you could have a JUnit test like this:

@Test
public void testIsImmutable() {
MutabilityDetector.assertImmutable(Contacts.class);
}

Then, if someone came along and added a setter method, or took away the final modifiers, the test would fail. This would give you confidence that not only are you correctly writing an immutable class now, but if anyone accidentally breaks it later, they'll be notified.

(Note that Mutability Detector would raise an error for ImmutableReminder by default, but that can be configured)

Javin @ String to Integer Java said...

@Graham, Thanks for writing such a useful tool, that can definitely complement some one's Junit test. I wish, if static analyzers can also do that or you may wish to let them know about your open source tool. Anyway, great work, please share link with us.

Anonymous said...

Hi Javin,

I have one Quick Question.If there is no Setter method then how will we set the value initially.

Gaurav said...

@Anonymous, value is initially set in constructor, when object is created. So Immutable object state remains same in its life.

Ashwin said...

Apart from the way mentioned here, is there any other way to make a class Immutable in Java?

Subrat said...

Hi,
We are creating our custom immutable class by the help of
1)making the class as final
2)providing the variable as final and initialize them in constructor
3)and providing only the getter methods

My doubt is String class is final and is immutable, I agree.But StringBuffer/StringBuilder class is also final that means it will not inherit by other class also.So internally what implementation has done so that it made the StringBuilder as mutable .
Please clarify my doubt.

Anonymous said...

@jo I think that is a fair point for the class in question. However it may help to declare it final if you have some methods which uses these variables within the class to prevent from modifying it as compiler would complain in that case

Anonymous said...

Is it require that immutable class must have Private constructor? I think no. As String in immutable class and we can create as many objects of it. But still in interviews people are asking why and why not to create the private constructor? Please help me to resolve my query.

Palak Joshi Raval said...

Hi anonymous..


I have one Quick Question.If there is no Setter method then how will we set the value initially.

You can refere the below link for that: http://howtodoinjava.com/2012/10/28/how-to-make-a-java-class-immutable/

You can pass the parameter value into the private constructor first time.

Parthasarathi Muthairam said...

Please suggest the below scnario to make immutable

public final class A{
public final B c;
public A(B c){
this.c = c;
}
public B getB(){
return c;
}
}

// Look at the below code

A a = new A(new B());

s.getB().setC(c); // it is change the state of the object. how can overcome that one.

indhu said...

hi,i just read your post and i am little confused about the re-usability that you have explained in the point no (4).you have explained that it is re-usable in point no (4)_ and if you notice again in the para after point no (4) you have explained that it cannot be re-used.Please clarify it.

Anonymous said...

Have getB return (B)B.clone()

Anonymous said...

Hi, As Indhu specified, can you please explain the two contradicting statements :
1. "4) Another important benefit of Immutable objects is reusability, "
2. "Apart from above advantages, immutable object has disadvantage of creating garbage as well. Since immutable object can not be reused and they are just a use and throw."

Post a Comment