Sunday, September 5, 2010

Remove that 'IF'

Recently, I was part of a team helping to acquire new Java resources for my organization. Our goal was to find few senior developers. I was surprised to see very few knew how Java (or OOP) can be used to remove those pesky procedural code specially those IFs and Switch statements.

Most of the time these conditional expressions contain one operand as constant (many time hard-coded value). This hard-coding or use of constant not only reduce understandability but also increase maintenance efforts such as adding, removing or updating a condition.

Example:
A menu controller program to handle File menu action could contain below method

public void performAction (String command)
{

if ("open".equals(command)) //action - "open"
{
//"open" action behavior definition
}
else if ("close".equals(command)) //action - "close"
{
//"close" action behavior definition
}
else if("exit".equals(command)) //action - "exit"
{
//"exit" action behavior definition
}

}

clearly there are maintainability issues, we must change the code if we want to add/ remove any action or if we want to change action behavior.

Solution:
Use of Command Pattern along with any resource resolving method (Map, ServiceLocator, DependencyResolver, etc.) can resolve this situation.

Below is just one of the method

MenuController

public class MenuController{

private Map commandMap;

public void performAction(String command)
{
Command cmdObject = commandMap.get(command);
if (cmdObject == null)
{
throw new CommandNotSupportedException(command + " not supported!");
}
cmdObject.execute();
}

}


Command Interface

public interface Command
{
public void execute();
}

Implementation for menu action "Open"

public class OpenCommand implements Command
{
public void execute()
{
//"open" action behavior definition
}
}

Clearly, as implementation defining the action are decoupled we need not to change controller for any action behavior change also actions can now easily added/ removed from the MenuControl using MenuController's Menu.

Maintainability issue resolved!

Thursday, January 3, 2008

Singleton - Serialization (Read) problem

Singleton Class that we discussed in Guaranteed Single Object Model post is almost guaranteed to be singleton but the problem comes when we are having solution environments with serialized objects.

Problem Description: There is a singleton class with object A, now this object is serialized on a stream, now what happens if we deserialize the object from the stream will there be more than one (single) objects? if yes how we can handle this issue.

Solution: yes indeed there will be two instances (or as many objects are read from the stream), we can't handle this issue in constructor or getInstance method as no calls are made by JVM for reconstructing an object from deserialization. To handle this issue Java provide users an option to define a protected readResolve method which is guaranteed to be called just after the deserialization and before reconstruction of the object.

Final Singleton Class

public class MySingleton{
private static MySingleton instance=null;
private MySingleton(){
//no code required - or any other initialisation code
}
public static synchronized MySingleton getInstance(){
if(instance==null){
instance=new MySingleton();
}
return instance;
}
public Object clone() throws CloneNotSupportedException{
throw new CloneNotSupportedException();
}

//method guaranteed to be called after deserialization and before object reconstruction
protected Object readResolve() throws ObjectStreamException{
return instance;//return the singleton object
}
//any other methods or code
}

Thursday, July 19, 2007

Two Cousins - String and StringBuffer

Introduction
If at all Strings exists then why do we need StringBuffer?
Untill now I pacified myself stating: its just a version of String with inbuilt buffer and dynamic size ability while compromising immutability and loosing its position of datatype.
But things changed when I started to optimize my code, and studied the relationship String and StringBuffer share.
Lets first discuss capabilities of each saperately to understand them and the relation they share.

String
String is one of the most powerful thing Java provided to programmers, it is a immutable object and treated as a datatype. Also it is the only object witch allows binary operation '+' and the assingnment operation '+='.
But still it is the Whipping Boy of Java performace, the reson behind is clear, it uses internally a char array to represent a String (witch takes heap memory, while all other datatype variable are created on stack) but there is no way to avoide Strings. Though there are things like String pool provided by JVM to share strings (internally by JVM not visible to user) but still '+' and '+=' costs a lot as each binary opration requires 3 string objects to be created (thus object creation cost as well as heap consumption).

StringBuffer
Its just like a String with an underlaying char array to store the string, but with dynamic extandability and utility methods like append, delete, insert and replace. With an option to define initial arraysize to reduce arraycopy calls. And to add to its stack - it is thread safe.
So are you getting something, its just like String but with methods to manipulate them more efficiently. As StringBuffer does not return a new objec for each manipulation operation like any append call will require only one StringBuffer object.

The Cousin Relationship
Use StringBuffer in manipulation and then use toString method to get the final String.
Well by now we all are smart enough to find out that, but wait a second its just a normal behaviour of any object's toString method where is the cousin relationship, do they really have Blood relation.
Yup they do share Blood, StringBuffers toString method returns a String object witch share the same underlaying array that of the StringBuffer, with a flag shared set to true. Thus no conversion cost is involved form converting a StirngBuffer to Stirng object.
They share the same char array till any other manipulation operation is performed on StirngBuffer, witch leads in creation of new underlaying array for StringBuffer object and invoking a System.arrayCopy method. The String object does not change and continue to point to the previous internal char array.

How does it happens
When toString method is called on StringBuffer it returns a new string as follows
return new String(this);

Thus calling constructor of String taking StringBuffer as argument, witch looks like this
public String (StringBuffer buffer) {
synchronized(buffer) {
buffer.setShared();
this.value = buffer.getValue();
this.offset = 0;
this.count = buffer.length();
}
}

Where setShared method set the StringBuffer's shared flag to true, witch in handled in every String manipulation opration in StringBuffer as
if (shared) copy();

Witch creates a new copy of char array and set StringBuffers storage pointer to it. (see copy methods code below)
private final void copy() {
char newValue[] = new char[value.length];
System.arraycopy(value, 0, newValue, 0, count);
value = newValue;
shared = false;
}

Singleton Pattern - "Guaranteed Single Object Model"

Introduction:
This blog only deals with implementing Singleton Pattern in Java.

Why? Whats the need?
Before we start, we must first understant the need of "single object model".
Say you want to access the printer/stream or any other resource then one would like to have a single handler for that resource to have greater controlling on its operations.
Or say you have an application accessing database, is it fine if all the modules of application access database with their own driver, in such conditions the singleton pattern is best suited.

Design Pattern and Singleton Pattern
Before we start our journy to singleton, lets first have a brife introduction about Design Patterns.
"Design Patterns are some guidelines, ganral rules, solution templates for common recurring problems"
And Singleton Pattern is a Creational Design Pattern - as it address and control cration of the object in question.
Definition: "A Design Pattern in witch at any time there is exactly one object/handler for any Class/Module"

Implementing Singleton in Java
According to definition for any class to be singleton there must not be more than one instance at any time, so first of all we must find a way to restrict users to create more instances of the object. This could be done my just making a private constructor, and providing a static method to access the instance of the object.

public class MySingleton{
private static MySingleton instance=null;
private MySingleton(){
//no code required - or any other initialisation code
}
public static MySingleton getInstance(){
if(instance==null){
instance=new MySingleton();
}
return instance;
}
//any other methods or code
}

So now no other class can create objects of this class and there can't be more than one instance, as we guarented in getInstance method. So is the job done? well yes and no - yes as it fulfills the definition and promery requirements and No as threading may create problems, and may lead to more than one instances.
Ohh thats now pretty easy, yeah we all know how to restrict threads to ruin all we have done, we all are smart people ;)
so just add synchronized keyword in the getInstance method, so our method signature becomes

public static synchronized MySingleton getInstance()

Well is it done yet? - Nop still one thing is there to trouble us, what if someone, someone having personal problem with your code ;), tries to make clone of your object, well you haven't given any clone method, but it is already there, remember Object.clone, and worst of all it has protected access so any subclass can be written and clone can be overridden, so just to avoid it add one clone method also.

So now we have our Singleton class with guaranted single object modle. Complete code for the class is below.

public class MySingleton{
private static MySingleton instance=null;
private MySingleton(){
//no code required - or any other initialisation code
}
public static synchronized MySingleton getInstance(){
if(instance==null){
instance=new MySingleton();
}
return instance;
}
public Object clone() throws CloneNotSupportedException{
throw new CloneNotSupportedException();
}
//any other methods or code
}

Using Volatile keyword efficiently

Java gives you a powerful keyword to address concurrent execution environments without writing your own mutual exclusion algorithm to monitor concurrent thread execution.


Though I must remind, this does come with some overheads and loss in efficiency, so before using volatile keyword one must fully understand the use, advantages and disadvantages of using volatile keyword.

What is Volatile?

Volatile is a Java modifier witch is a hint to the compiler about nature of the variable. It tells the compiler that given variable can be changed by something beyond the control of the program. It tells compiler to handle this variable differently than normal variables.

What different handling of Volatile variables done in Java?

When a variable is defined volatile, Java compiler and JVM do two things differently.

1. Compiler does not optimize the expressions and statements involving that variable.

2. Synchronization (concurrent execution with mutual exclusion) of the variable is done by JVM.

When to use Volatile and when to design your own monitor?

Now as we know volatile gives a hint to compiler that given variable can be changed by something beyond the control of the program, so then why Sun provided synchronization keyword.
As volatile keyword is handled by compiler and JVM, it involves some overheads and we don’t have control over handling of this critical section problem.

Thus when to use volatile and when to use custom monitors can be answered in this way:
Use Volatile keyword whenever the variable represents some type of system or environment dependent variable.
For Example: clocks and simple counters.

And use custom monitors for those variables witch are changed by some other code and not by the environment, or for those variables for witch you want greater control on concurrent execution.
For example: Linked List, Queues etc.