Thursday, December 19, 2013

java class immutable

Benefits of making a class immutable
Lets first identify benefits of making a class immutable. Immutable classes are
  1. are simple to construct, test, and use
  2. are automatically thread-safe and have no synchronization issues
  3. do not need a copy constructor
  4. do not need an implementation of clone
  5. allow hashCode to use lazy initialization, and to cache its return value
  6. do not need to be copied defensively when used as a field
  7. make good Map keys and Set elements (these objects must not change state while in the collection)
  8. have their class invariant established once upon construction, and it never needs to be checked again
  9. always have “failure atomicity” (a term used by Joshua Bloch) : if an immutable object throws an exception, it’s never left in an undesirable or indeterminate state
How to make a class immutable
  1. Make all fields final and private
  2. Don’t provide “set” method
  3. Don’t allow subclasses to override methods, declare class final
  4. If need return immutable instance variable, always return a copy of it
  5. Using Collections.unmodifiableList() to get a read-only list, same for set and map.  This is to avoid somebody using reflection to get private field directly.
  6. stop reflection to access private field, using a SecurityManager and a sufficiently restrictive security policy. //TODO

Another way to make class immutable is to use cglib
cglib’s ImmutableBean allows you to create an immutability wrapper similar to for example Collections#immutableSet. All changes of the underlying bean will be prevented by an IllegalStateException

No comments:

Post a Comment