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)

jQuery error- simpleLightbox not found

Faced a unique error with jQuery today.  I was using jquery-1.3.2.min.js and jquery-simplelightbox.js. Which were included properly in the jsp file, but still the javascript was throwing the error that simpleLightbox function is not found.

on a close look it was found that after adding both the JS files, an additional jsp file was added which was again adding jquery-1.3.2.min.js, hence overriding the original jQuery object.

Lesson learnt- Always make sure that jQuery js file is added only once, especially if we are modifying the object.

How does database (oracle) joins handle filter condition

I was wondering how does database interpret join queries. When we create a join between 2 tables in Oracle, with some additional filter condition on one or both tables, will oracle join the tables first and then filter or will it filter the conditions first and then join.

For example I have 2 simple queries

Query 1:

select e.name, d.name from employee e, department d
where e.dept_id=d.id and e.salary>50000;

Query 2:

select e.name, d.name from
(select * from employee where salary>50000) e, department d
where e.dept_id=d.id;

Now which is a better option?

I posted my doubts on a couple of forums and did some googling, and this is what I found

“Both are same”

An easy way to check this out id to use “explain plan for” clause, which tells you how actually oracle interprets your query after optimization.

explain plan for
select e.name, d.name from employee e, department d
where e.dept_id=d.id and e.salary>50000;
select * from table(dbms_xplan.display());

output was same as

explain plan for
elect e.name, d.name from
(select * from employee where salary>50000) e, department d
where e.dept_id=d.id;

Using Javadoc for documentation

What is Javadoc? Most of the times people confuse it with the actual HTML documentation for the Java code. This is somewhat true but not entirely. Javadoc, itself is not the documentation, it is a tool from SUN Microsystem that helps you generate the documents.

How does it work? Javadoc allows developers to add documentation for a code in the java file itself in some specially formatted comments. The tool will read these comments and create a HTML document file.

Why do we use Javadoc? Why can’t we just create documents on our own? Well That is possible. Javadoc is there to make your life simpler as a developer. It helps you keep your code and documentation information in the same file. Just imagine if you are keeping the documentation separately, everytime you make a change in code, you ill need to modify the documentation also. What if someone misses it? If it is in the same file it is easier to maintain and hard to miss.  Most importantly, you are not writing the whole documentation, but just adding some quick comments which will be interpreted by the Javadoc tool. Lot more easier and faster than actually writing the documentation.

How to implement it? Simple, just add some specially formatted comments in your code

Class Level comments

@author : Author of the class
@version : automatically provide accurate version and date updates.
@since :  Describes when this functionality has first existed.

Method Level

@param : method or constructor argument names and description
@return :  What does your method returns
@throws : Does this method throw an exception
@deprecated : 	Describes an outdated method.

General Commets

@see : Adds 'See also' entry
@link : Adds an inline link with a label for users of your API documentation

The final code will look something like

import java.util.ArrayList;

/**
 * This is a Java Class to find anagrams. Any class level description goes here
 *
 * @author kamal
 * @version 1.0
 * @since 21-Sep-2011
 */
public class test{

/**
 * This is the main method method
 *
 * use {@link #findAnagrams(String)}
 * @param str
 * 		Any param description goes here
 */
public static void main(String str[])
{
	try
	{
		 String finalString="TestString";
		 test t =new test();
		 t.findAnagrams(finalString);
	}
	catch(Exception e) {
	   e.printStackTrace();
	}
}

/**
 * This is another method and we will add the description here
 *
 * @param input
 * 		Any param description goes here
 * @return
 * @throws NullPointerException
 */
private ArrayList findAnagrams(String input) throws NullPointerException
{
	ArrayList retList=new ArrayList();
	if(input.equals("")) throw new NullPointerException();
	printAnagrams(retList, "",input);
	return retList;
}

/**
 * Yet another method description goes here
 *
 * @param retList
 * @param prefix
 * @param word
 */
public void printAnagrams( ArrayList retList, String prefix, String word) {

if(word.length() <= 1) {
	retList.add(prefix + word);
} else {
for(int i = 0; i < word.length(); i++) {
String cur = word.substring(i, i + 1);
String before = word.substring(0, i); // letters before cur
String after = word.substring(i + 1); // letters after cur
printAnagrams(retList,prefix + cur, before + after);
}
}
}
}

and your javadoc comments will look like

image link

testdoc

Restricting recipient emails in postfix

Had a requirement today to restrict emails from our postfix server to only to some specific domains/ email addresses. It turned out to be pretty simple

At the end of /etc/postfix/main.cf just add

smtpd_recipient_restrictions =
   check_recipient_access hash:/etc/postfix/access
   permit_auth_destination
   reject

and at the end of /etc/postfix/access add the domain names/ email addresses which can accept emails

kamalmeet.com OK
abcd@gmail.com OK

Now update postfix db

postmap hash:/etc/postfix/access

and finally restart service

service postfix restart

That’s it

Creating a basic Android app

I am exploring Android application development for some new projects so thought about sharing my notes here. So far it is turning out to be fun and very simple :).

I am using eclipse for development so first of all we will need to install ADT. Follow the steps mentioned here

http://developer.android.com/sdk/eclipse-adt.html

Once we have ADT installed, creating first android project is pretty simple. Create a new android project (right click->new project->Android project).

In the project creation window, provide details-

Provide name say test_project, Choose target say 2.1, package- com.kamalmeet.android.test and activity- test. Skip test project creation and click Finish

Now we will run this project on emulator. Just go to your project and run as ‘android application’, this will give a “Hello World Test” message.

Now let us see what happened when we created and executed the project. When we created a a new project it created some files. Here are the important ones to get started

We will see AndroidManifest.xml in base project directory. This is the root file of our project. This contains details of the activities, services etc for our project. For now you are seeing only one activity under application node in this xml file. Also note the package declaration in manifest, this is the base package of our project.

Now we will check our package under src/ folder. Lets take a quick look into com.kamalmeet.android.test. We see the activity java file test.java. It extends the  parent android.app.Activity class, and has one method it overrides, that is onCreate. No points on guessing that this is the first method getting called when activity loads. For now it has just one line setContentView(R.layout.main);

To understand meaning of this line, lets move to gen/ folder, which has the same package and a autogenerated R.java file. This file gets automatically generated on compilation. It provides a unique Id to all our visible contents. For example, we can see an inner class as layout which has an int main value.

What does this main value corresponds to? Checkout res/ folder. This has all out UI related stuff like images, view XMLS etc. under res we have res/layout/ folder. This is where we have our UI XML, in this case main.xml. As you can see android supports XML defined UI like just Flex, XAML etc. In addition we can define

You can see one node as LinearLayout and a child node of TextView. This is responsible for what we see on UI. We can see test being set as android:text=”@string/hello”. It picks up value from /res/values/strings.xml. In this XML you can see a string node where name is set as hello with value as “Hello World, test!” Change it to any value say “My first Android app” and re-run the application. Simple. Now we can go ahead and play around with this simple UI app.