hashCode and equals method

In java world, hashCode & equals method plays a very important role.

Uses of equals():-

In java, equals() method used to assure equality of object and it should follow mathematics rule of equality.

  1. Reflexive: Always, a = a. In Java, a.equals(a) should always be true.
  2. Symmetric: If a = b, then b = a. In Java, if a.equals(b) is true, then b.equals(a) should be true.
  3. Transitive: If a = b and b = c, then a = c. In Java, if a.equals(b) and b.equals(c) is true, then a.equals(c) should be true.

In java equals() method defined in Object class, which returns true if memory locations of objects  (i.e object references)  are same else false. In real world two object whose object references are not same, can be equal. lets consider java class Employee with attributes (name, id, address). 

then Employee e1 = new Employee(“ABC”, 10, “xyz Nagar”)

Employee e2 =  new Employee(“ABC”, 10, “xyz Nagar”)  both object (i.e e1 & e2) should be equal as their attributes value are the same.

Now if we are checking equality of e1 & e2 without overriding equals() in Employee class (i.e e1.equals(e2) or e2.eqauls(e1)) will return false.

Overriding equals():-

To achieve correct behavior, we need to override equals method as below:

public boolean equals(Object o) {
        if(o == null)
            return false;
        if (o == this)
           return true;
        if (getClass() != o.getClass())
            return false;
        Employee e = (Employee) o;
        return (this.getId() == e.getId());

Uses of hashCode():-

We must override hashCode() when we override equals(). Why hashCode should also be overridden when equals is overridden? Because, they both serve the same purpose but in different contexts. hashCode() method is used in hashtables to determine the equality of keys.

if two objects are equal, that is obj1.equals(obj2) is true then, obj1.hashCode() and obj2.hashCode() must return same integer.

hashCode() method returns integer value for object, which is used to find bucket location index in HashTable & HashMap like data-structure, while equals() used in HashSet and other set data structure to restrict duplicate entry insertion in Set.

Sometime hashCode() & equals() works together when we try to get value of some key inside HashTable or HashMap. For example, Just imagine, you are storing multiple different object  with different key inside HashTable. There might be possiblity that hashcode for few keys can generate same index location in bucket. If index location of keys in bucket are same then  any call of  get(key) will search key array (Keys stored in Map.Entry array) sequentially & corresponding equals() method  of key class will get invoke to check equality, if it is true then corresponding value for key stored in Entry will get returned.

equals() and hashCode() Using in ORM:-

Always make sure that if you are working with ORM, use getters of instance variables in hashCode() and equals(). This is for reason, in ORM,  fields might be  lazy loaded and not available until unless their getter methods called.

For example, In our Employee class if we use e1.id == e2.id. There might be possibility  that id field is lazy loaded. So in this case, one might be zero or null, and thus resulting in incorrect behavior.

But if uses e1.getId() == e2.getId(), we can be sure even if field is lazy loaded; calling getter will populate the field first.


Thread synchronization, object level locking and class level locking

Object level locking:-

Synchronization means synchronizing state changes of Object and that we can achieve it via synchronizing block in any java class.

Suppose we have a java class with few instance variable whose values get changed i.e state of objects for that class get changed time to time. To avoid data corruption or inconsistency, we do synchronization of threads who tries to modify the state of object. Synchronization assures that if multiple threads try to modify the state of same object simultaneously then they need to go under the process of acquiring object lock first. Once any one thread got lock for particular object all others need to wait until unless lock acquired thread is not releasing lock. Same time if N Threads trying to enter in synchronized block with separate objects, No one thread will wait because of all will get lock for separate object.

For example, Suppose there are 100 threads which trying to work with same object say obj1, which has some synchronized block, and all 100 threads trying to enter in that block.That point of time only one thread gets lock & will execute synchronized block.

Now suppose all 100 threads trying to enter in synchronized block of java class with separate object instances say obj1, obj2……. obj100, Then all 100 threads can get entered in block because lock is on current obj & they can get executed at the same time.

Class level locking:-

When class loader loads class in JVM, it creates one object of the class which know as ‘class’ and can be accessed as javaclassname.class . For example, if we have our class say ABC.java then when ABC gets loaded in JVM & ABC.class object gets created by JVM.

Now suppose if we are synchronizing block on the basis of ABC.class or static method locks get associated with ABC.class object. Now if multiple threads trying to enter into same synchronized block, they need to acquire lock on ABC.class object. if any one thread have acquired lock all ready others need to go in waiting queue until unless lock is not released.

I have just included theory, how does things works behind the scene. Hope it clears your doubt.




Java Monitoring API (Jamon)

JAMon is a free Java monitoring API , used to monitor your application or fine tuning your application performance.

Do following steps to use JAmon in your code

  • copy jamon-2.7.jar in classpath
  • Add these lines to your code where to like to monitor

// start the JAMon monitor
Monitor mon = MonitorFactory.start(“Your Label”);

your codes go here

// stop the JAMon monitor

  • After you have deployed your app, go to http://localhost:port/jamon/jamonadmin.jsp to see all the statistics.
  • JAMon for stand alone Java application:
    //1) print to log
    Monitor mon=MonitorFactory.start(“your label”);  // you can provide any label name
    ..code to monitor…
    //2) html table
    String htmlTable=MonitorFactory.getReport();
    //3) raw data
    String[] header=MonitorFactory.getHeader();
    Object[][] data=MonitorFactory.getData();


Please feel free to drop me a message if you have any question. 🙂 🙂 🙂

How To Load Multiple Spring Bean Configuration File

Loading Multiple Spring Bean Configuration File

 Put all spring xml files under project classpath. 

Define one main module beans configuration file. Say AppContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	<import resource="classpath:AppServicesContext.xml"/>
        <import resource="classpath:AppConnectionContext.xml"/>
        <import resource="classpath:AppModuleA.xml"/>
        <import resource="classpath:AppModuleB.xml"/>

Now you can load a single xml file like this :

ApplicationContext context = 
    		new ClassPathXmlApplicationContext("AppContext.xml");


Using Property File in Spring

Often times, Spring developers keep there configuration value in XML file itself. Say for example DB setting as

<bean id=”dataSource”

<property name=”driverClassName” value=”com.mysql.jdbc.Driver” />
<property name=”url” value=”jdbc:mysql://localhost:3306/rr” />
<property name=”username” value=”root” />
<property name=”password” value=”password” />

But, in a corporate environment, deployment detail is usually only can ‘touch’ by your system or database administrator, they just refuse to access your bean configuration file directly, and they will request a separate file for deployment configuration, for example, a simple properties, with deployment detail only.  To fix it, one can use spring API called PropertyPlaceHolderConfigurer.

Example of PropertyPlaceHolderConfigurer

Create a properties file (database.properties), include your details (say database details), put it into your project class path.



Declare a PropertyPlaceholderConfigurer  bean in bean configuration file and map to the ‘database.properties‘ properties file you created just now.

	<property name="location">

At End our beans configuration file look like as

<beans xmlns="http://www.springframework.org/schema/beans"

	  <property name="location">
	<bean id="dataSource"
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />


Hope this helped you…… 🙂