Thursday, December 26, 2013

Immutable Class in Java

An immutable class is a class whose instances cannot be modified. All of the information contained in each instance is provided when it is created and is fixed for the lifetime of the object.

The biggest advantage of immutable objects is that they are inherently thread-safe; and therefore they do not require any synchronization. Therefore, immutable objects can be shared freely. Immutable classes are easier to design, implement, and use in comparison to mutable classes. They are less prone to error and are more secure.

To make a class immutable, follow the following rules:

1. Don’t provide any mutator methods, i.e. the methods that modify the object’s state.

2. Ensure that the class can’t be extended. This prevents careless or malicious
subclasses from compromising the immutable behavior of the class by behaving
as if the object’s state has changed. Preventing subclassing is generally accomplished
by making the class final or having a private constructor with a public static factory method.

3. Make all fields final. It is necessary to ensure correct behavior if a reference
to a newly created instance is passed from one thread to another without
Synchronization.

4. Make all fields private. This prevents clients from obtaining access to mutable
objects referred to by fields and modifying these objects directly.

5. Ensure exclusive access to any mutable components. If the class has any
fields that refer to mutable objects, ensure that clients of the class cannot obtain
references to these objects. Make defensive copies and return them instead.

Lets Take an example:











public final class Planet {



    public Planet (double masss, String namee, Date datee) {

       mass = masss;

       name = namee;

      //Make a defensive copy of the Mutable object Date

       date = new Date(datee.getTime());

    }



    public double getMass() {

      return mass;

    }



    public String getName() {

      return name;

    }



    /**

    * Returns a defensive copy of mutable object

    */

    public Date getDate() {

      return new Date(date.getTime());

    }



    private final double mass;



    private final String name;



    private final Date date;

  }





The above code snippet is an example of an Immutable class. Notice, how we have made defensive copies of the mutable state ‘date’.

The only real disadvantage of immutable classes is that they require a
separate object for each distinct value. Creating these objects can be costly,
especially if they are large.

As discussed in rule 2 above, one alternative of creating an immutable object is to use a public static factory method to return the immutable instances rather than using a constructor. The real advantage that you get out of this approach is the flexibility of creating strategies like, reusing instances or caching instances etc instead of creating a new instance every time. Sometimes, this flexibility also aids performance. Static factory is a preferred way of creating immutable objects.

Tuesday, December 10, 2013

It is a common use case to create an activity which returns a particular state for a specific amount of time and then revert back to its original state. For example you want to suspend a particular user on your website for say, 60 seconds (maybe because he’s submitting a form too fast – a strategy a lot of forms support). There are many such use cases possible especially when that application is using huge amount of cache. One way to do it would be with database which is not only highly in-efficient but way too cumbersome. If we could create a data structure that could retain its state for a specific time and then revert back, it would be killer.

I would present such a Boolean data structure that could be used to validate a condition for a specific time and then it would revert back to its original status.

One of the important design decisions has been to make this data structure immutable. One instance would represent just one state. Also, in this implementation I have used constructors rather than static factory method to return state objects, but nothing stops us from having a static factory method for our state objects.

Lets look at our class now:








public class AutoRevertingBoolean {



  //the present status

  private final boolean present;

  

  //This is the default status and this is what

  // the object would be reverted to. Since this is boolean

  //it can be either true/fase, but why this property

  //is important would be explained in subsequent posts.

  private final boolean revertTo;

  

  //the time till which the present state would

  //be preserved before reverting back

  private final long waitInMillisBeforeReverting;

  

  //time that preserves the invocation time

  //of this data structure

  private long time = 0;



  /**

   * Constructor that creates the state object but the users

   * would need to explicitly start the ticker by invoking

   * the {@link #startMeasuring()} method

   @param present

   @param revertTo

   @param waitInMillisBeforeReverting long time in milliseconds

   */

  public AutoRevertingBoolean(final boolean present, final boolean revertTo,

      final long waitInMillisBeforeReverting) {

    this.present = present;

    this.revertTo = revertTo;

    this.waitInMillisBeforeReverting = waitInMillisBeforeReverting;

  }



  /**

   * Constructor that also starts the ticker as soon as this

   * object is created.

   @param present boolean

   @param revertTo boolean 

   @param waitInMillisBeforeReverting long time in milliseconds

   @param startNow

   */

  public AutoRevertingBoolean(final boolean present, final boolean revertTo,

      final long waitInMillisBeforeReverting, final boolean startNow) {

    this(present, revertTo, waitInMillisBeforeReverting);

    this.startMeasuring();

  }



  /**

   * Returns the present state of the object

   @return boolean Will return the present state if the 

   * specified time has not elapsed or else would return the

   * default state of the object. 

   */

  public boolean get() {

    return System.currentTimeMillis() < time + waitInMillisBeforeReverting ? present

        : revertTo;

  }



  /**

   * starts the timer for this data structure

   */

  public void startMeasuring() {

    if(!(time > ))

      time = System.currentTimeMillis();

  }



  public static void main(String[] args) {



    AutoRevertingBoolean obj = new AutoRevertingBoolean(true, false, 3000);

    //need to explicitly call this for the constructor that we have used.

    obj.startMeasuring();

    foo(obj);

    obj = new AutoRevertingBoolean(true, false, 5000,true);

    //need not explicitly start measuring the time

    foo(obj);

  }



  private static void foo(AutoRevertingBoolean obj) {

    System.out.println("Starting.....");

    long startTime = System.currentTimeMillis();

    for (int i = 0; i < Integer.MAX_VALUE; i++) {

      if (!obj.get())

        break;

    }

    System.out.println("Done in:" (System.currentTimeMillis() - startTime)+" milliseconds.");

  }



}




The code is pretty self-explanatory. The main method gives away its usage pattern. There are several ways to extend this data structure and as we move forward we would try to improve and evolve this data structure.