Tuesday, July 28, 2009

Immutable Objects

An immutable object is an object, that once created, stays in the same state. Immutable objects improve thread safety, aid security, and avoid unauthorized changes to state.

Immutable objects are objects, that once created, stays in the same state. Immutable objects improve thread safety, aid security, and avoid unauthorized changes to state. There are many immutable types in Java: String, Integer, Float, etc.

Thread safety is assured for such objects as the only one thread can create these objects and the state of the object is static and unchangeable until the object is dereferenced (i.e. ready for garbage collection).

Please note that some make a mistake in believing something is immutable but has a reference to a changeable object. For example, the following class is not thread safe because the creator of Foo or any thread that calls getList() can add/remove contents of the list. Note also that the synchronized method is both useless and inappropriately reducing liveness.


@notthreadsafe
public class Foo{
private ArrayList list;
public Foo( ArrayList list){
this.list = list;
}
public synchronized ArrayList getList(){
return list;
}
}

1 comment:

  1. I cannot think of a better example of a class that should have been immutable than Date. Every time I use it I die a little inside.

    ReplyDelete