Friday, May 13, 2011

What is the best way to implement Singleton pattern

We use singleton pattern when we need only one instance to be created. Why do we need to create only one instance.
* Object creation and destruction might be a high expensive task.
* Object might share some information need to be accessed through out the system. If multiple instance are there. Different different classes will see different different values.

We can find many articles on how to implement Singleton pattern. The best solution I found so far is below.

public class Singleton {

private static class SingletonHolder {
static Singleton instance = new Singleton();
}

public static Singleton getInstance() {
return SingletonHolder.instance;
}

}

We can guaraty that above is lazily loaded and thread safe. if you don't need it to be loaded lazily use below. that is the simplest.


public class Singleton {

private static Singleton instance = new Singleton();

public static Singleton getInstance() {
return instance;
}

}


As I remember in head first design pattern book, after saying so many stories they finally has given double locking solution like below. they talked much about volatile and double locking there.

class Singleton {

private static volatile Singleton instance;

public static Singleton getInstance(){
if(instance == null){
syncronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}

}


OK Still I can't guarantee that only one instance is created for all scenarios. With java reflection we can call private constructor and create a new object as below.


Class cl = Class.forName("Singleton");
java.lang.reflect.Constructor[] c = cl.getDeclaredConstructors();
c[0].setAccessible(true);
Singleton instance2 = (Singleton) c[0].newInstance();


There is a way to prevent that. We can implement Singleton by using enums. By default enums are singleton. As I found Enums can't be instantiate through reflection.


enum EnumSingleton {
SINGLETON;

public void test() {
System.out.println("This is also a singleton " + this);
}

private EnumSingleton(){
System.out.println("Constructing the singleton ...");
}

}

you can get the singleton object through EnumSingleton.SINGLETON and call test() method.

So what do you think what is the best last one or first one. I prefer the first one.

Thursday, May 5, 2011

AOP with Spring

Spring makes AOP easy. Before explaining Spring AOP let's discuss about AOP and why do we need that. AOP modularise cross cutting concerns to one place. Then what is a cross cutting concern? ....
Logging and Security are the common examples for cross cutting concerns. For example in authorisation we need to check permission for the user when the user try to execute some method that need to be secured. If there are many this type of method that checks security, it will be duplicated every where and code will be tangle and scattered. In AOP it has their own terminology which explain those points.

1. Join Point
A join point is a execution point that has cross cutting concern. This might be a method or some exceptional case.

2.Point Cut
Point cut is the expression that explain about Joint points. So one point cut may represent many join points. For example below point cut represent all methods in com.xyz.service or sub package.

@Pointcut(value = "execution(* com.xyz.service.*.*(..))")
private void anyMethod() {
}


3.Advice
Advice is a code fragment that need to be implemented at defined point cut. For example think we need to have a log every time before executing above mentioned point cut. That means before calling any method in com.xyz.service or sub package we need to have a log message. we can define that advice below.

@Before("anyMethod()")
public void logMessage() throws Throwable {
logger.debug("Going to execute com.xyz.service method");
}


We can see different type of advice as below.
* Before advice
* After returning advice
* After throwing advice
* After (finally) advice
* Around advice



4. Aspect
Aspect modularise similar concerns spread every where into one place. In spring Aspect is a class which has @Aspect annotation.

Let's try to implement this using AOP.

public class MyService implements IMyService{

private static final Logger logger = LoggerFactory.getLogger(MyService.class);

public void someSecuredMethod(String userName) {
logger.debug("Hi " + userName + ". I have a secret to tell you");
}
}

@Aspect
public class MyAopAspect {

private static Logger logger = LoggerFactory.getLogger(MyAopAspect.class);

@Pointcut(value = "execution(public * someSecuredMethod(..))")
private void anyPublicOperation() {
}


@Around("anyPublicOperation() && args(userName)")
public void checkPermission(ProceedingJoinPoint pj, String userName) throws Throwable {
if (userName.equals("che guevara")) {
pj.proceed();
} else {
logger.error("User {} doesn't have permission", userName);
}
}
}


In above example I have used around advice. With around advice aspect can decide whether it need to execute doSomething() method or not. If you don't call ProceedingJoinPoint.proced(), doSomeThing() will never be invoked.

get working example with test cases here.