Friday, September 4, 2009

Why we need an immutable object?

I want to explain it with 2 examples.

First one:
class A{

private StringBuffer name;

public void setName(StringBuffer Name){
name=Name;
}

public StringBuffer getName(){
return name;
}

}

class B{

A a=new A();
StringBuffer temp=new StringBuffer("Anai");
a.setName(temp);
System.out.println(a.getName());
temp.append('a');
System.out.println(a.getName());
}

output:
Anai
Anaia

It is completely against "encapsulation" concept.It is mainly because of mutable class(StringBuffer).

Second one:
see the immutable class which i mentioned it on my previous post.Suppose you want to maintain table of past data which never going to be changed then this kind of implementation will be helpful.

Main Advantage of Immutable is ThreadSafe

2 comments:

  1. @Anai.
    Nice example. Let me add something to that as to why the such a class is thread safe. Issues with thread safety can be classified into two.

    1. issues inherent to thread safety
    2. issue that are accidental - that is, these issues are a result of eliminating the inherent issues with thread safety.

    The only inherent issue with thread safety is race condition and as a result of eliminating race condition, we get issues like dead lock and live lock

    This classification is really important and must be kept in mind before you freeze the design. After all if there is no disease in the first place, you need not have medicece. Your design should be in such a way that you avoid getting the disease of race condition in the first place. Thats what anai does when he uses an immutable class for implenting a table.

    Now as to why an immutable class is thread safe, race condtion ocurss only when you are sharing a data. With an immutable class, if you are going to modify a data, you are going to get a new copy of that, so the inherent rae condition is not present...

    Thank You

    ReplyDelete
  2. Anai, a nice way to start blog, man!!! Very very informative, please keep things posted, so that we can learn more :)

    ReplyDelete