Pages

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, seewhy 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

As 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.

publicfinalclass Contacts {

privatefinalString name;

privatefinalString mobile;

publicContacts(String name, String mobile) {

this.name = name;

this.mobile = mobile;

}

publicStringgetName(){

return name;

}

publicStringgetMobile(){

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 likejava.util.Date, despite
storing Date into final field it can be modifiedinternally, 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.

publicfinalclass
ImmutableReminder{

privatefinalDate remindingDate;

publicImmutableReminder (Date remindingDate)
{

if(remindingDate.getTime() <System.currentTimeMillis()){

thrownewIllegalArgumentException("Can not
set reminder” +

“ for past time: "+ remindingDate);

}

this.remindingDate =newDate(remindingDate.getTime());

}

publicDategetRemindingDate() {

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.

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.

30 comments
:

1) All the fields must be private and preferably final2) Ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private3) Fields must be populated from the Constructor/Factory4) Don't provide any setters for the fields5) Watch out for collections. Use Collections.unmodifiable*. Also, collections should contain only immutable Objects6) All the getters must provide immutable objects or use defensive copying7) 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

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;

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.

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.

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?

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)

@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.

Hi,We are creating our custom immutable class by the help of1)making the class as final2)providing the variable as final and initialize them in constructor3)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.

@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

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.

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.

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."

Hi Javin,What is the necessity of making the member variables final?as anyways we are not providing any setters to alter the value,and in case of mutable fields, we are returning a clone to the callee.

Could some one explain me why fields has to be private? IMHO making them final would suffice .and Why are we making class final ? Subclass cann't change the values of Superclass in any manner. It only inherits the values from the Superclass. The reason for making String class was different . Jave guys dint want people to extend the functionality of String class , thats why they made it final. It will be very helpfull if someone shed light on this :)

/* Name of the class has to be "Main" only if the class is public. */public final class coffee{ {/*private*/ public final String coffee;/*private*/ public final String code;public void coder(String coffee,String code){this.coffee=coffee;this.code=code;}public String getcoffee(){return coffee;} public String getCode(){return code;}//do//{System.out.println("It's time to drink coffee");//}//While(coffee==coffee)}

public static void main(String []args) { // System.out.println("Hello World"); coffee c=new coffee(); c.coder(); }}Could any one help me to solve this code?Kinda getting errors and have doubt near do while block

I also like to use immutable value objects but they can be a hassle without tool support and the tools I could found had problems, so I just released my own open source tool for generating java value objects that used 100% standard java features and is extremely customisable. You can check it out at "http://valjogen.41concepts.com". Let me know what you think?