Monthly Archives: June 2010

Single object for Singleton pattern


I have explained the basics of singleton pattern here https://vtkrishn.wordpress.com/2010/03/26/singleton-pattern-revisited/

The design goes like this

1) private constructor
2) static method to return the single objects

In this post I am going to explain some additional restrictions on this pattern

1) Lazy initialization with double lock mechanism

2) Early initialization

3) Serialization

4) ClassLoaders

5) Restrict Cloning

Lazy instantiation using double locking mechanism

The standard implementation shown in the code above is a thread safe implementation, but it’s not the best thread-safe implementation because synchronization is very expensive when we are talking about the performance. We can see that the synchronized method getInstance does not need to be checked for synchronization after the object is initialized. If we see that the singleton object is already created we just have to return it without using any synchronized block. This optimization consist in checking in an un-synchronized block if the object is null and if not to check again and create it in an synchronized block. This is called double locking mechanism.

In this case case the singleton instance is created when the getInstance() method is called for the first time. This is called lazy instantiation and it ensures that the singleton instance is created only when it is needed.

//Lazy instantiation using double locking mechanism.
class Singleton
{
 private static Singleton m_instance;

 private Singleton()
 {
 System.out.println("Singleton(): Initializing Instance");
 }

 public static Singleton getInstance()
 {
 if (m_instance == null)
 {
 synchronized(Singleton.class)
 {
 if (m_instance == null)
 {
 System.out.println("getInstance(): First time getInstance was invoked!");
 m_instance = new Singleton();
 }
 }
 }

 return m_instance;
 }

 public void doSomething()
 {
 System.out.println("doSomething(): Singleton does something!");
 }
}

Early instantiation using implementation with static field

In the following implementattion the singleton object is instantiated when the class is loaded and not when it is first used, due to the fact that the m_instance member is declared static. This is why in this implementation we don’t need to syncronize any portion of the code. The class is loaded once this guarantee the unicity of the object

//Early instantiation using implementation with static field.
class Singleton
{
 private static Singleton m_instance = new Singleton();

 private Singleton()
 {
 System.out.println("Singleton(): Initializing Instance");
 }

 public static Singleton getInstance()
 {
 return m_instance;
 }

 public void doSomething()
 {
 System.out.println("doSomething(): Singleton does something!");
 }
}

Serialization

If the Singleton class implements the java.io.Serializable interface, when a singleton is serialized and then deserialized more than once, there will be multiple instances of Singleton created. In order to avoid this the readResolve method should be implemented. See Serializable () and readResolve Method () in javadocs.

 public class Singleton implements Serializable {
 ...

 // This method is called immediately after an object of this class is deserialized.
 // This method returns the singleton instance.
 protected Object readResolve() {
 return getInstance();
 }
 }

ClassLoaders

If you have multiple classloaders(possibilities in case of servlet container) then the patterns will allow for multiple instances to be created which is not expected
To overcome this you have to have the custom implementation like

private static Class getClass(String classname)
 throws ClassNotFoundException {
 ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
 if(classLoader == null)
 classLoader = Singleton.class.getClassLoader();
 return (classLoader.loadClass(classname));
 }
}

Restrict Cloning

You can overcome cloning of the singleton object by explicitly throwing cloneNotSupportedException

public Object clone() throws CloneNotSupportedException {
 throw new CloneNotSupportedException();
 }

If we try to access the above singleton object using reflection then you will get

Exception in thread "Main Thread" java.lang.IllegalAccessException: Class com.example.thread.Main can not access a member of class com.simple.NormalClass with modifiers "private"
 at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:65)
 at java.lang.Class.newInstance0(Class.java:349)
 at java.lang.Class.newInstance(Class.java:308)
 at com.example.thread.Main.main(Main.java:10)

if you are using java 1.5 and above you can use enum type which takes care of all the above


public enum Singleton{
INSTANCE;

public static void print(){
System.out.println("hi");
}

public class Main{

public static void main(String[] args) {
Singleton.INSTANCE.print();
}
}
}

OODesign concepts


Some of the main oodesign principles are available here
I hope this will help developers understand the oo concept more efficiently.

http://www.oodesign.com/design-principles.html

Refactoring the code


I suggest this link for those who wanted to refactor their code without any side effects

http://www.refactoring.com/catalog/index.html

Testable code


Found a good article on writing testable code

http://www.methodsandtools.com/archive/archive.php?id=103

Know some hashcodes


Some of the hashcodes of interest’s are in java wrappers

Boolean – hashCode() – 1231 for ‘true’ and ‘1237’ for ‘false’
Integer – hashCode() – will return the primitive int value
Byte – hashCode() – primitive int value of the byte is returned as hashcode
Charater- hashCode() – primitive int value of the byte is returned as hashcode
Long – value of the following expression

(int)(this.longValue()^(this.longValue()>>>32))

Magic Numbers a glance


Ever wonder how files are identified correctly as jpeg, gif or even class file for that matter by the OS.

Its all magic.. 🙂

Magic numbers are those which are prefixed at the start of the file in ASCII code to identify the file format.

Some of the common magic numbers are

Class bytecode starts with hex CAFEBABE
GIF image files have ‘GIF89a‘ (47 49 46 38 39 61) or ‘GIF87a‘ (47 49 46 38 37 61)
JPEG image files begin with ‘FF D8‘ and end with ‘FF D9'
PNG image files begin with “\211 P N G \r \n 32 \n” (89 50 4E 47 0D 0A 1A 0A)
ZIP files begin with ‘PK‘ (50 4B)
PDF files start with ‘%PDF‘ (25 50 44 46)

Overloading and Overrriding – revisited


Overloading

is applied only within a class by simply

  1. having the same name for the method but
  2. passing different parameters list

what can happen in Overloading is that

  • the number of arguments to the method can change
  • the same name with different parameter list can be defined in the super class also

what cannot happen in Overloading is that

  • same name and same no of arguments as the compiler does the differentiation using only the method signatures that comprises of method name and the arguments passed
  • same name with different return type cannot qualify and throws compile time error as ‘the Duplicate method defined’ for the same reason as above

example

 //Allowed
 public int display(){
 System.out.println("returning int");
 return 0;
 }
 //Allowed
 public int display(int a)throws IOException{
 System.out.println("returning int with a");
 return 0;
 }

 //Allowed
 public int display(int a,int b){
 System.out.println("returning int with a and b");
 return 0;
 }

 //Allowed
 public int display(char a) throws IOException{
 System.out.println("returning int with char a");
 return 0;
 }

 //Allowed
 public int display(String a) throws IOException{
 System.out.println("returning int with char a");
 return 0;
 }

 //Not Allowed - Duplicate method
 public int display(char a) throws IOException{
 System.out.println("returning int with char a");
 return 0;
 }

 //Not Allowed - Duplicate method
 public String display(char a) throws IOException{
 System.out.println("returning int with char a");
 return "hi";
 }

use Overloading only if the method does the same logic with different parameters

Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass methods—they are new methods, unique to the subclass

Overriding

is applied only when the sub class tends to modify the behavior of a method in the super class

  1. having the same name for the method
  2. having the same parameter list
  3. having the same return type

what can happen in Overriding is that

1. the access modifier can be less restrictive than the one in super class

  • if the superclass method is public, the overriding method must be public
  • if the superclass method is protected, the overriding method may be protected or public
  • if the superclass method is package, the overriding method may be package, protected, or public
  • if the superclass methods is private, it is not inherited and overriding is not an issue

2. the overriding method in the subclass class cannot throw any exception that is broader than the exception thrown by the super class

Solving NumberFormatException


Often we tend to parse the integer value from a String object using Integer.valueOf(strValue) or Integer.parseInt(strValue). This will work as far as we pass the string like ‘1234567’ without any grouping.. The problme arises only if we have grouping on the string which is parsed..

Bump..

parseInt() and valueOf() method throws NumberFormatException for this.

So how to resolve this,

rewrite the code and make use of parse() method in java.text.NumberFormat class

String str = "123,456";
 int i = 0;
 try {
 i = NumberFormat.getNumberInstance().parse(str).intValue();
 } catch (ParseException e) {
 e.printStackTrace();
 }
 System.out.println(i);