The concept
of immutable is if we have a reference to an instance of an object, than the
content of the instance cannot be altered. So the object state of immutable
class cannot be changed once it is constructed.
Advantages
of immutable class
1.
Immutable classes are
thread-safe and there is no synchronization issue.
2.
Immutable classes can be easily
shared or cached without having to copy or clone them as there state cannot be
changed ever after construction.
3.
Always have failure atomicity,
if immutable object throws and exception it never left in an undesirable or
indeterminate state.
4.
Immutable class can be used as
key of HashMap.
How
to create immutable class
1.
Declare your class as final
2.
Make all the member variable of
class as private and final.
3.
Do not provide any setters,
pass value only through constructor.
4.
If immutable class encapsulate
mutable object than create a copy of mutable object never store the reference
to the original object
5.
Never return mutable abject,
return a copy of object.
6.
Avoid method which can change
mutable object.
Code snippet –
/**
* BrokenStudent Immutable class.
* @author Manoj
*/
public final class BrokenStudent {
private final String firstName;
private final String lastName;
private final Date dob;
BrokenStudent(String firstName, String lastName, Date dob) {
this.firstName = firstName;
this.lastName = lastName;
this.dob = new Date(dob.getTime());// copy of object
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Date getDob() {
return new Date(dob.getTime()); // copy of object
}
}
Note –
In java java.lang.String are immutable and the wrapper classes for primitive
type are immutable. Some other important immutable classes are –
java.lang.StackTraceElement
java.util.Collections
java.util.Arrays
java.util.Locale
java.util.UUID
Why
String are immutable in java
1.
String are easily shared over
network like network connections, database connection URL, Username/password etc.
So this can be easily changed if String will be mutable.
2.
String is used as argument in
class loading it could load wrong class if it get changed.
3.
The main object is design
because String are created in “String Intern Pool” when we create a variable it
searches the pool to check whether is it already exist. If it is exist, then
return reference of the existing String object. If the String is not immutable,
changing the String with one reference will lead to the wrong value for the
other references. This memory utilization increase the performance.
very usefull in full details thanks
ReplyDelete