Monthly Archives: December 2011

Exception Handling- Basic Principles

Do not catch unchecked exceptions
Exceptions in java can be divided into checked and unchecked exceptions. Java compiler would force you to catch the checked exceptions but not the unchecked exceptions. Unchecked exceptions includes error and Runtime exception. These are the conditions in which program will not be able to handle the flow even if these are caught, so better let the JVM throw error and print stack rather than trying to handle these.

Error- A condition which occurs outside the program and causes failure, example, hardware failure.
Runtime Exceptions- An exception condition which occurred because of bad programming practice or unexpected input from user. For example, null value assigned to a variable being used or division by zero. Ideally these errors should be handled by code checks and not exception handling.

This means we should avoid catching superclass Exception as that will cover RuntimeExcpetions

Throw more relevant exceptions
Exception handling is done at multiple levels in code. For example you have, action->Process->Data layer. Now you might catch an exception in Database layer, but you might want to handle the exception actually in Action layer. So rather than throwing back filenotfound or sqlexception, you can create a DAOException and throw it instead. which will travel through Process layer and then to Action. This will help Action to handle fewer exceptions which are relevant at that layer.

Caveat- You might want to make sure you are passing all the relevant information back to the upper layers.

Using multiple try-catches
Instead of using one big block of try catch, create multiple blocks for better handling of exceptions. Make sure to take care of flow, once an exception is handled, the code will move to next try block.

Handle Exceptions late in code flow
Throw exceptions back to higher layers rather than absorbing them at lower layers. E.g. If an exception is caught at DAO layer, you might still want to throw it back to action layer for better handling.


Extend Exception and not Throwable

Here is the hierarchy of Exception class structure. Ideally we should try to extend a class as low as possible in hierarchy

Object->Throwable
Throwable->Exception and Error
Exception-> RuntimeExceptions and [other exceptions like filenotfound]
RuntimeException-> ArtithmeticException, NullPointerException

References:
http://wikijava.org/wiki/10_best_practices_with_Exceptions
http://docs.oracle.com/javase/tutorial/essential/exceptions/

Forgot MySql password?

Forgot the root password for mysql database. Here are easy steps to recover

1. Restart MySql database without password in safe mode
/etc/init.d/mysql stop
mysqld_safe --skip-grant-tables &

2. Change root password 
mysql -u root
mysql> use mysql;
mysql> update user set password="mypassword" where User='root';
mysql> flush privileges;
mysql> quit

**please note that the password might be in encrypted form. use PASSWORD('some_pass') method 
mysql> update user set password=PASSWORD('mypassword') where User='root';

3. Restart database
/etc/init.d/mysql stop
/etc/init.d/mysql start

References: http://www.cyberciti.biz/tips/recover-mysql-root-password.html

Taking Mysql Backups

If you need to take a backup of myql database in sql format, it is pretty simple

mysqldump -u myDatabaseUsername -p Password >backup.sql

You will get the backup.sql file which you can restore anywhere

mysql – u myDatabaseUser -p -D databseName < backup.sql or simply execute file from the mysql prompt @backup.sql References: http://www.roseindia.net/mysql/mysql_backup_restore.shtml

For creating user and providing privileges
http://www.debuntu.org/how-to-create-a-mysql-database-and-set-privileges-to-a-user

Using Clone with Singleton pattern

A friend came up with an interesting question today. Can we clone the singleton class object? Practically it is of no value, but theoretically the question is interesting. Practically not useful, because why would someone want to make the singleton class cloneable? The whole concept of singleton class is to avoid creation of multiple objects for a class.

But the question do bring up interesting concept. Can we clone a singleton object? As we know every class inherits from Object class, which does have a protected method clone. And if we want to make sure that our class’s objects can be cloned, we will need to implement cloneable interface and implement clone method. But then you are actually implementing creation of clones and violating basic principle of single-ton pattern.

A little googling showed that we can actually implement the cloning accidentally. That is, say there is a class X which is clonable and our developer extends this class in the singleton class (why would someone do that?). In that case, our Singleton class do implement clonable, though not intentionally. Though we do not have a clone method for our singleton class, unless we override it. So still we are safe.

Still, if we want to make sure that our singleton class never becomes clonable, a sureshot way to do that is to implement clonable and force an exception if someone do try to clone objec of singleton class, he will get the exception.



public class SingletonTest implements Cloneable{

	private static SingletonTest singletonObject=null;
	private SingletonTest(){
		
	}
	
	public static SingletonTest getInstance()
	{
		if(singletonObject == null)
		{
			return new SingletonTest();
		}
		return singletonObject;
	}
	
	public Object clone() throws CloneNotSupportedException
	{
		throw new CloneNotSupportedException();
		
	}
	
}


Banker’s algo for deadlock avoidance

What is deadlock?

From wikipedia- A deadlock is a situation where in two or more competing actions are each waiting for the other to finish, and thus neither ever does. It is often seen in a paradox like the “chicken or the egg“. The concept of a Catch-22 is similar.

So what is a deadlock in terms of operating system job scheduling. It is same, there are multiple jobs which are trying to gain control of resources and end up in a situation where each process is waiting for some resiurce which is being held by another process.

How to avoid such situations? Banker’s algoirthm is the answer. As the name suggest, the algorithm uses intellegence shown by a banker in order to maintain safe amount of cash in the bank, so that bank never runs into a situation where it has no money to fulfill its customer needs.

A very simple example will be, say the bank has 60K amount. There are 3 customers A, B and C. A needs 30K for its project, B needs 25K, and C needs 40K. Now we know that bank can fulfill need of all three customers, but not at once. So ideally the bank will fulfill one customer’s need at a time, wait for the customer to return the money (we will ignore interest for simplicity, and we will assume money will be returned by cistomer as soon as project is finished though in real workd cstomer might need some time), and then move on to next. Which is not effective use of money as customers will need to wait while others finish. In practical world, not all the money will be needed for projects in one go, so the bank can ask customers how much amount they will need at what stage, and at what time they can return the money, and try to organize the finances in a way that all customers can finish there projects in best possible time. The same kind of logic is used by job-scheduler of on operating system to make sure all jobs gets finished in best possible time, avoiding deadlock.

Lets say customers provide this data to bank

Customer A: Need 10K at start

Customer B: Need 10K at start

Customer C: Need 10K at start

The bank sees it can afford to give this money to all the customers as it will still have enough money to fulfill needs of all the customers.

In stage 2, all customers again come up with a demand of 10K. Now the bank sees if it will allocate all the money, it will run out of money with none of the projects being successfully completed, hence no point of recovery. So it must deny some of the customer. Safest bet will be to refuse the amount to C and tell it to wait till bank has enoght fund. Allocate the money to A and B, as it will still have enough money to give to these customer to finish the project.

So C is put on hold and A and B moves on with the project. Now say A comes up with demand of 10K, which bank will fulfill and A will be able to finish project successfully and return 30K. Now bank can provide money to C, as it knows it will have sufficient funds for other customers.

The same intellegence is used by an OS to make sure the system never runs out of resources.

Testing your website in different browsers- Cross browser compatibility

There are many services available on the internet which will let you know how you website/ webpage will appear on different browser or different version of same browser or same browser in different Operating systems. I tried looking for some free services for a project. Two services that look good

http://browsershots.org/

Pros- FREE, supports 100+ combination of browser and OS, No Registration required- you are good to go by just providing site link

Cons- Slow, incomplete results for some cases

https://browserlab.adobe.com/

Pros- Free, Fast, Chose browser at runtime and change

Cons- Limited browser selection, Registration required, Did not work for some of the mentioned browsers(may be temporary issue)