Skip to main content

Better ways to implement Singleton in Java

Singleton Design pattern restrict creation of only once instance of a Class. That means inside a single JVM only one instance of the Singleton Class will be created.  In java we have broadly two options to implement Singleton.

1)
2) Lazy Creation of the Object Instance: Here the instance is created on first invocation.

Following example demonstrate how to implement Singleton in Java.

Method 1: Early Creation of Object Instance
public class SingletonClass {
private static final SingletonClass INSTANCE = new SingletonClass(); //Private Constructor private SingletonClass() { //Do nothing } public static SingletonClass getInstance() { return INSTANCE; } }
Here the instance is created ahead even before calling the Class. We need to provide a private constructor otherwise Java Compiler will add a default Constructor.

Method 2: Lazy Creation of Object Instance
public class SingletonClass {
   private static volatile SingletonClass INSTANCE = null;
private SingletonClass() {
       //Do nothing
   }
public static SingletonClass getInstance() { if (INSTANCE == null) { synchronized (SingletonClass.class) { if (INSTANCE == null) { INSTANCE = new SingletonClass(); } } } return INSTANCE; } }
In Lazy creation apporach the instance of the Class will not be created unless the getInstance() method is called. The above implementation we are checking if the INSTANCE is null twice, once before the synchronized block and once after the block. This is known as  Double - Checked Locking. The volatile keyword here is very important and would work only in Java 5+.

Above examples one can still create multiple instances under the following conditions,
1) Cloning the Object from the Object returned by Singleton.
2) Serializing and Deserializing.
3) If multiple Class loader are used in an Application then each Class Loader can have multiple instance of the same object.

We can extend the above two example  to take care (1) and (2 )
by  prevent cloning(Implement Cloneable interface) and throw Exception from clone() method.
Serialization by implementing  (Serializable Interface) and implementing readResolve() method to return the instance.

Other simple and better option is using Java enum. If we use Enum then we do not have to take care of Clone or Serializable issues. JVM make sure enum instances are Singleton in a single Class Loader.



public enum SingletonClass {
  INSTANCE;
}
 //Which is equivalent to 
public final class SingletonClass { 
  public final static SingletonClass INSTANCE = new SingletonClass(); 
  }
}


Comments

Popular posts from this blog

Converting Java Map to String

Java Collections framework, String manipulation etc is something that we often encounter in Development process.
For processing collections (like checking null/empty, Intersection, Disjunction) We do have some of the very use full libraries.

Some of the Collection related libraries are Apche Commons Collections and Google  Collections(Guava).

Problem Use Case

This article explains how to convert a Java Map to String(and vice versa) using different libraries and technique.

One way is to use StringBuilder(Or String) and loop though the Map and build the String by applying some sort of separator ( for key:value and entry). Here we have to take care of the null value etc.

Without Any Library
If we want to convert the map to a String with key value separator and also individual entry seperator in the resulting String, we have to write code for that. For a simple Map, we have to iterate though the map, take care of the null values etc. Following is a sample to get String built out from Map C…

Masking Credit Card number in Java

Sometimes we need to mask crucial information like Credit Card Numbers, CVV numbers etc before storing  or logging the information. This example mask Credit Card Number (Except last 4 Digit) from a Text which contains information along with Credit Card Number.

The following example demonstrates how we can easily mask the credit card with Matcher and Pattern Classes. This Sample Code uses Matcher and Pattern.
Pattern Used in this sample is not optimized for Credit Card Numbers, this pattern will get any numerical numbers in the String Content.  Based on the Credit Card Type a more efficient and Strict RegEx can be used to mask the Credit Card.
/**Mask the Credit card number but last four digit value **/   Pattern PATTERN = Pattern.compile("[0-9]+"); String message = content; Matcher matcher = PATTERN.matcher(message); String maskingChar = "*"; StringBuilder finalMask = new StringBuilder(maskingChar); while …

Invoking EJB deployed on a remote machine

Invoking EJB deployed on a remote machineIn case we are calling remote ejb( ejb deployed on remote machines),The JNDI lookup might lookup like,Properties env = new Properties();env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");env.put(Context.PROVIDER_URL, "XX.XXX.XX.XX:1099");env.put("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces"); Context ctx = new InitialContext(env);If we are calling local ejb then we can simply create InitialContext without any parameters.Like,Context ctx = new InitialContext();