Monthly Archives: March 2010

Difference between HashMap and IdentityHashMap

Most of the time I use HasMap whenever a map kinda object is needed. When reading some blog I came across IdentityHashMap in Java. It is good to understand the differences between the two because you never know when you will see them flying across your code and you trying to find out why is  this kinda Map is used here.

IdentityHashMap as name suggests uses the equality operator(==) for comparing the keys. So when you put any Key Value pair in it the Key Object is compared using == operator.

 import java.util.HashMap;
 import java.util.IdentityHashMap;
 import java.util.Map;

public class IdentityMapDemo {

public static void main(String[] args) {
 Map identityMap = new IdentityHashMap();
 Map hashMap = new HashMap();
 identityMap.put("a", 1);
 identityMap.put(new String("a"), 2);
 identityMap.put("a", 3);

hashMap.put("a", 1);
 hashMap.put(new String("a"), 2);
 hashMap.put("a", 3);

System.out.println("Identity Map KeySet Size :: " +  identityMap.keySet().size());
 System.out.println("Hash Map KeySet Size :: " + hashMap.keySet().size());

On the other hand HashMap uses equals method to determine the uniqueness of the Key.


instead of equality operator.

When you run the above code the result will be

Identity Map KeySet Size :: 2
Hash Map KeySet Size :: 1

The Keysize of Identity Map is 2 because here a and new String(“a”) are considered two different Object. The comparison is done using == operator.

For HashMap the keySize is 1 because K1.equals(K2) returns true for all three Keys and hence it keep on removing the old value and updating it with the new one.

These both Maps will behave in same manner if they are used for Keys which are user defined Object and doesn’t overrides equals method.


Posted by on March 24, 2010 in Java, Java Collections


Life Cycle of Java Objects

Java an Object Oriented language is able to comply to the approaches which are closer to real world solutions of commonly known problems. To get a better understanding of Objects one should know the life cycle of them. An Object goes through various phases in its life span.

Phases in Objects Life Cycle

Object Life Cycle

An average developer only makes point of two to three phases in Object’s life which includes Created, In Use and Finalized which results in inefficient performance of the application. Understanding all phases of Object life is very important if developer wants his code to be efficient and bug free. Proper knowledge of these phases will also ensure less memory leaks.

Creation of an Object means allocation of memory, calling constructor and initializing its properties. When the Object is created it is ready for use and lives in memory heap of the JVM. Creating an Object is simplest and is known to every novice developer.

public Dog getDog(){
Dog dog = new Dog(); // creation of Object Dog
return dog;

In Use: Any Object that is held by any strong reference is said to be in use. In the following code Dog object is in use which has a string reference dog.

Dog dog = new Dog();// Here dog is strong reference to Dog Object

We can have multiple strong references of any Object. When the object is in use it is never approached by GC.  The difference between Created state and In Use state is  that when an Object is created it may be or may not be in use. You can just create an Object and forget it without having its reference. In this case the Object directly comes under Unreachable state.

//Creation of Dog Objects
Dog dog = new Dog();
Dog dog2 = new Dog();
dog = null;// Object refereed by dog directly goes to Unreachable state

Invisible Objects can cause unnecessary memory blockage and can impact the performance as well. Invisible references are strong references which are not accessible while the reference and Object are both are in scope.

public void execute(){
Object obj = new Object();
}catch(Exception e){


In the above example when the execution of the code comes to the infinite while loop it may seem that the above Object referenced by obj is out of scope and is eligible for GC but in fact it lives in the same stack frame and occupies memory in heap area. Now if this Object(referred by obj) is very large in size and there are a lot like this before while loop then it can cause  serious memory blockage and there are chances to get  OutOfMemoryException.

Fix: To fix this we have to explicitly set the references to null after using them.

An Object becomes unreachable when there are no more references to it and it can’t be accessed. Such an object is eligible for GC but when that decision is made by GC itself.

Dog dog = new Dog(); //line 1
dog  = null; //line 2

In above code the Object at line 1 becomes unreachable at line 2. The GC is also smart enough to detect circular refrences and collect them too.

Dog dog = new Dog(); //line 1
Owner owner = new Owner(); //line 2
dog.addOwner(owner); //line 3
owner.addPet(dog); //line 4
dog = null; //line 5
owner = null; //line 6

In the above code snippet both Dog and Owner objects becomes eligible for GC at line 5 and 6. Though both the objects are accessible if we get any one of them but it is not possible to access any of them and hence they become unreachable.

After getting recognized as unreachable Object it moves to collected state. It is just a phase before its deallocation. If the Object has finalize method then it is marked for finalization otherwise it directly moves to finalized state.

Here an extra delay happens if the Object has finalizer method. So to make the process of freeing the occupied memory space think before writing finalize method.

After Object’s finalized method is called and then also it is unreachable then it is in finalized state. The finalize() method is only called once and it’s better to handle any clean up in your code elsewhere because the resources are blocked till finalizer is called by the GC.

The deallocated state is the final step in garbage collection. If an object is still unreachable after all the above work has occurred, then it is a candidate for deallocation. Again, when and how deallocation occurs is up to the JVM.

Leave a comment

Posted by on March 17, 2010 in Java