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.

 

 

 

Android Fragment Example

Fragment:-
A fragment is an independent component which can be used by an activity. A fragment encapsulate functionality so that it is easier to reuse within activities and layouts.

A fragment runs in the context of an activity but it has its own life cycle and typically its own user interface. It is also possible to define fragments with an user interface, i.e. headless fragments.

Fragment can be dynamically or statically added to an activity.

While working with fragment in android, one need to think for following

1) Communication between Fragment.

2) Communication between Fragment & Activity.

3) Life Cycle of Fragment.

Please wait to complete the post, sorry for inconvenience.

SurfaceView in Android

To create custom view in android, we extends View and implements onDraw() method. Extending view is fine for custom view but just imagine, what about if you want to draw something multiple times like animation. Android provides SurfaceView for animation purpose.

For View, the onDraw method is triggered by the system when it knows that the Canvas is safe to draw on. It can set things up for us before calling onDraw, and then clean up when it is done executing. Since we need to do drawing on our own schedule, we need a view class that will let us do this set up and clean up ourselves. That class is called SurfaceView.

Now as I said we are going to do drawing on our own schedule so there should be some intimation that the view has been created or view has been destroyed , so that accordingly we can do set up or  clean up task.

To intimate user program Android has provided callbacks method of SurfaceHolder.

Here SurfaceHolder plays a very important role as we know for View class, Canvas object is automatically get passed to onDraw() method.But for SurfaceView we need to get Canvas, once SurfaceView is created and draw on that canvas.

Here Going to provide simple example for Bouncing ball using surface view.

Create a surface view child class by extending it

public class GameBoard extends SurfaceView implements SurfaceHolder.Callback
{
private Paint p;
MyThread thread;
int x =16,y=16;
int dx = 5, dy = 5;
Bitmap bitmap = null;
public GameBoard(Context context)
{
super(context);
p = new Paint();
getHolder().addCallback(this);
thread = new MyThread(getHolder(), this);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
bitmap = bitmap.createScaledBitmap(bitmap, 10, 10, false);
// TODO Auto-generated constructor stub
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,int height)
{

}
@Override
public void surfaceCreated(SurfaceHolder holder)
{

thread.setRunning(true);
thread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
// TODO Auto-generated method stub
boolean retry = true;
thread.setRunning(false);
while(retry)
{
try
{
thread.join();
retry = false;
}catch(Exception e)
{
e.printStackTrace();
}
}
}
public void update(Canvas canvas)
{
p.setColor(Color.BLACK);
p.setAlpha(255);
p.setStrokeWidth(1);
canvas.drawRect(0, 0, getWidth(), getHeight(), p);
/*Random r = new Random();
p.setStrokeWidth(6);
p.setColor(r.nextInt());
canvas.drawPoint(x,y, p);*/

canvas.drawBitmap(bitmap, x, y, p);
if(x >getWidth() - bitmap.getWidth() || x - bitmap.getWidth() < 0)
dx = -dx;
if(y > getHeight() - bitmap.getHeight() || y - bitmap.getHeight()< 0)
dy = -dy;

x +=dx;
y +=dy;

}

class MyThread extends Thread
{
SurfaceHolder holder;
GameBoard game;
boolean running = false;
public MyThread(SurfaceHolder holder,GameBoard game)
{
this.holder = holder;
this.game = game;
}
@Override
public void run()
{
Canvas canvas;
while (running)
{
canvas = null;
canvas = this.holder.lockCanvas(null);
if(canvas != null)
{
synchronized (this.holder)
{
this.game.update(canvas);

}
this.holder.unlockCanvasAndPost(canvas);
}

}
}
public void setRunning(boolean b)
{
this.running = b;
}
}
} 

Create an Activity say GameActivity with following content

public class GameActivity extends Activity
{
     @Override
     protected void onCreate(Bundle savedInstanceState) 
         {
           super.onCreate(savedInstanceState);
           
            setContentView(new GameBoard(this));
 }
}

Declare activity in manifest file and run the application.

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
mon.stop();

  • 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…
    System.out.println(mon.stop());
    
    //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"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
 
	<import resource="classpath:AppServicesContext.xml"/>
        <import resource="classpath:AppConnectionContext.xml"/>
        <import resource="classpath:AppModuleA.xml"/>
        <import resource="classpath:AppModuleB.xml"/>
</beans>

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”
class=”org.springframework.jdbc.datasource.DriverManagerDataSource”>

<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” />
</bean>

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.

database.properties

        jdbc.driverClassName=com.mysql.jdbc.Driver
	jdbc.url=jdbc:mysql://localhost:3306/rr
	jdbc.username=root
	jdbc.password=password

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

<bean 
	class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="location">
	  <value>database.properties</value>
	</property>
</bean>

At End our beans configuration file look like as

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  <bean
	 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	  <property name="location">
		<value>database.properties</value>
	  </property>
	</bean>
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

</beans>

Hope this helped you…… 🙂