Thursday, January 19, 2012

immutability in Java

Summary:  Immutable objects have a number of properties that make working with them easier, including relaxed synchronization requirements and the freedom to share and cache object references without concern for data corruption. While immutability may not necessarily make sense for all classes, most programs have at least a few classes that would benefit from being immutable.

An immutable object is one whose externally visible state cannot change after it is instantiated. The String, Integer, and BigDecimal classes in the Java class library are examples of immutable objects -- they represent a single value that cannot change over the lifetime of the object.

Benefits of immutability
Immutable classes, when used properly, can greatly simplify programming. They can only be in one state, so as long as they are properly constructed, they can never get into an inconsistent state. You can freely share and cache references to immutable objects without having to copy or clone them; you can cache their fields or the results of their methods without worrying about the values becoming stale or inconsistent with the rest of the object's state. Immutable classes generally make the best map keys. And they are inherently thread-safe, so you don't have to synchronize access to them across threads.

Freedom to cache
Because there is no danger of immutable objects changing their value, you can freely cache references to them and be confident that the reference will refer to the same value later. Similarly, because their properties cannot change, you can cache their fields and the results of their methods.
If an object is mutable, you have to exercise some care when storing a reference to it. Consider the code in Listing 1, which queues two tasks for execution by a scheduler. The intent is that the first task would start now and the second task would start in one day.

When to use immutable classes

Immutable classes are ideal for representing values of abstract data types, such as numbers, enumerated types, or colors. The basic numeric classes in the Java class library, such as Integer, Long, and Float, are immutable, as are other standard numeric types such as BigInteger and BigDecimal. Classes for representing complex numbers or arbitrary-precision rational numbers would be good candidates for immutability. Depending on your application, even abstract types that contain many discrete values -- such as vectors or matrices -- might be good candidates for implementing as immutable classes.



Another good example of immutability in the Java class library is java.awt.Color. While colors are generally represented as an ordered set of numeric values in some color representation (such as RGB, HSB, or CMYK), it makes more sense to think of a color as a distinguished value in a color space, rather than an ordered set of individually addressable values, and therefore it makes sense to implement Color as an immutable class.
Should we represent objects that are containers for multiple primitive values, such as points, vectors, matrices, or RGB colors, with mutable or immutable objects? The answer is. . . it depends. How are they going to be used? Are they being used primarily to represent multi-dimensional values (like the color of a pixel), or simply as containers for a collection of related properties of some other object (like the height and width of a window)? How often are these properties going to be changed? If they are changed, do the individual component values have meaning within the application on their own?

Events are another good example of candidates for implementation with immutable classes. Events are short-lived, and are often consumed in a different thread than they were created in, so making them immutable has more advantages than disadvantages. Most AWT event classes are not implemented as being strictly immutable, but could be with small modifications. Similarly, in a system that uses some form of messaging to communicate between components, making the message objects immutable is probably sensible.


Guidelines for writing immutable classes
Writing immutable classes is easy. A class will be immutable if all of the following are true:
  • All of its fields are final
  • The class is declared final
  • The this reference is not allowed to escape during construction
  • Any fields that contain references to mutable objects, such as arrays, collections, or mutable classes like Date:
    • Are private
    • Are never returned or otherwise exposed to callers
    • Are the only reference to the objects that they reference
    • Do not change the state of the referenced objects after construction