banner



Java How To Create Immutable Class

Writing or creating immutable classes in Java is becoming popular day by day, because of the concurrency and multithreading advantage provided by immutable objects. Immutable objects offer several benefits over a conventional mutable object, especially while creating concurrent Java applications. 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 don't know what is immutable class or object is, Immutable objects are those, whose state can not be changed once created like java.lang.String , once created can not be modified like trim, uppercase, lowercase.


All modifications in String result in the new objects, see why String is immutable in Java for more details. In this Java programming tutorial, we will learn, how to write an immutable class in Java or how to make a class immutable.

By the way, making a class immutable is not difficult on the code level, but its the decision to make, which class is mutable or immutable which makes a difference. I also suggest reading, Java Concurrency in Practice to learn more about concurrency benefits offered by Immutable objects.

And, If you are new to Java then you can also check out these free Java programming courses to learn Java from scratch in a guided and structured way. This is one of the best free, and up-to-date courses to learn Java online.

What is an immutable class in Java? Example

What is Immutable class and object, how to create Immutable in Java with example As said earlier, Immutable classes are those classes, whose object can not be modified once created, it means any modification on an immutable object will result in another immutable object. the best example to understand immutable and mutable objects are, String and StringBuffer.

Since A string is an 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 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 a few disadvantages, an 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. The state of immutable object can not be modified after construction, any modification should result in a new immutable object.

2. All fields of the 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 an immutable object by violating few rules, like String has its hashcode in thenon final field, but its always guaranteed to be the same. No matter how many times you calculate it because it's calculated from final fields, which is guaranteed to be the 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 ways of creating immutable classes in Java, where all fields of class also remain immutable like String in the above case. Sometimes you may need to write an immutable class that includes mutable classes like java.util.Date, despite storing Date into the final field it can be modified internally if the internal date is returned to the client.

In order to preserve immutability in In such cases, it's advised to return a copy of the original object, which is also one of the Java best practices. here is another example of making a class immutable in Java, which includes mutable member variables.

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) An 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 the above advantages, immutable object has disadvantage of creating garbage as well. Since the immutable objects 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 an immutable class in Java that involves mutable fields. Don't forget to read more about the concurrency benefit offered by Immutable object in one of the best Java books recommended to Java programmers, Concurrency Practice in Java.

Related Java programming concepts and tutorials

Java How To Create Immutable Class

Source: https://javarevisited.blogspot.com/2013/03/how-to-create-immutable-class-object-java-example-tutorial.html

Posted by: dumaisention.blogspot.com

0 Response to "Java How To Create Immutable Class"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel