This study is part of work on
Concurrency Programming in Java.
Immutable Object- state cant be altered.
The wrapper classes,
Byte, Character, Short, Integer, Long, Float and Double are all immutable.
Strings are immutable.
How to construct an immutable object?
- Simplest way would be to mark all the fields as final.
- Declare the member fields as private and not to provide any setter methods, and letting it all to be initialized through constructor only.
In case the object gets a reference to other object, get the reference to a copy(clone) of that object. This way the referenced object is hidden from the user, thus the object is immutable as whole.
public class Order {
private String orderId;
private int quantity;
private BookProperties bookProperties;
public Order(String orderId,int quantity,BookProperties props){
this.orderId=orderId;
this.quantity=quantity;
this.bookProperties=(BookProperties)props.clone();
}
public String getOrderId(){
return orderId;
}
public int getQuantity(){
return quantity;
}
public BookProperties getBookProperties(){
return bookProperties.clone();
}
}
Note: Do not let the object to be reference before the object is completely constructed, this could be difficult in concurrent environment.
Advantages of Immutable objects
Immutable objects are state consistent value containers, thus
- Immutable object can never encounter conflicts or inconsistencies when multiple threads accesses it.
- Immutable objects are more suitable for HashTable keys. If the 'key' object state could be altered then we may lose the mapping.
Immutable objects allow shared references, thus
- Duplicate objects can be avoided improving space efficiency. (eg)String
Why is String Immutable?
String is a value object like primitive variables whose value should never be changed. Making String an immutable object is linked to Security and space concern, may be it
- in javac which is written on java and it uses lots of String objects containing parsed name that are not to be altered. The reason was felt so strong that String was made immutable in JLS.
- in JVM's SecurityManager allowing the code to access resources. Consider a situation where we have to validate a legitimate site and then let him/her connect to it. If the String mutable, immediately after verification the host name could be altered and connection would be made to a different server.
- An important feature of immutability is, the object reference can be shared for space efficiency and yet have no access restrictions or syncronization concern. A same string object can be referenced from many other objects.
How do I make my method return an immutable reference?
- Wrap the reference in an immutable wrapper class and return that.
- Return an immutable interface to the original data.
- You can return an Iterator with a dummy remove method.
- In case of Collections, use the available Collection.unmodifiableCollection methods.