Sunday, September 5, 2010

Java 5.0 Multithreading feature - Callable and Future

One of the very important feature of Java 5.0 is Callable Interface and Future.
The problem with Runnable interface or Thread class in multithreading was you can return any value from the thread.
But this drawback was removed in Java 5.0 with Callable Interface and Future.
In the code below, Callable<Interger> in CallableExample, the thread will return 'Integer' and this Integer value can be retrieved using Future object as shown in CallableExampleTest.

1. Callable Implementation:
----->

import java.util.concurrent.Callable;

/**
*
* @author vinitpatwa
*/
public class CallableExample implements Callable<Integer> {

private String word;

public CallableExample(String word) {

this.word = word;
}

public Integer call() {

return getWord().length();

}

public String getWord() {
return word;
}
}

<-----

2. Testing the Callable implementation
----->
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
*
* @author vinitpatwa
*/
public class CallableExampleTest {

public static void main(String args[]) throws Exception{

ExecutorService pool=Executors.newFixedThreadPool(1);
List<Future<Integer>> set=new LinkedList<Future<Integer>>();
String[] strArray={"Texas", "California", "Ohio"};
for(String word:strArray){

Callable cal=new CallableExample(word);
Future<Integer> future=pool.submit(cal);
set.add(future);

}

for(Future<Integer> future:set){
System.out.println("Length of word is : "+future.get());
}
}
}

<-----

Thursday, September 2, 2010

Design Patterns Tutorial

1. Singleton Pattern
-------------------------------------
A Singleton is a class that can be instantiated only one time in a JVM per class loader. Repeated calls always returns the same instance. Ensures that a class has only one instance, and provide a global point of access. It can be an issue if singleton class gets loaded by multiple class loader or JVMs

An example of Singleton Pattern

public class OnlyOne{

private static OnlyOne one=new OnlyOne();

//private constructory
//This class can not be instantiated from outside and prevent subclassing
private OnlyOne(){}

public static OnlyOne getInstance(){
retrun one;
}

}


2. Factory Pattern
-------------------------------------
A factory method pattern is creational pattern. The creational patterns abstract the object instantiation process by hiding how the objects are created and make the system independent of the object creational process.
Factory pattern returns one of the several product subclasses. You should use a factory pattern, if you have a super class and number of subclasses, and based on some data provided, you have to return the object of one of the subclasses, But the calling code is unaware of the actual implementation.
Factory pattern reduces the coupling or the dependencies between calling code and the called object.

The abstract factory pattern is one level of abstraction higher than factory method pattern, which means it returns the factory classes.

3. FlyWeight Design Pattern:
-------------------------------------
When we create string objects String s1="A"; String s2="A".
It will check if it is already in the string pool, if it is there, then it will get it from there. Flyweight are like Shared objects and reusing them will have considerable performance gain


4. Decorater Design Pattern:
-------------------------------------
Decorator pattern attaches responsibilities to objects at runtime.
Java.io classes uses Decorator design pattern to construct different combination of behavior at runtime based on some basic classes.

File file=new File("C:/temp");
FileInputStream f=new FileInputStream(file);
BufferredInputStream output=new BufferredInputStream(f);

Decorator design pattern add or restrict functionality of decorator object before or after forwarding the request.
At runtime 'output' which is decorator objects forward the method calls to it's decorated object 'f'

5. Observer Pattern (publisher - subscriber design pattern)
-------------------------------------
(one publisher - one / multiple subscriber)
Intent of this design pattern is to define one to many dependency so that when one object(i.e. Publisher changes it's state, all it's dependents(i.e. all it's subscribers) are notified and updated successfully.

6. Reactor Design pattern
-------------------------------------
Unlike Observer pattern, Reactor design pattern handles multiple even sources (multiple publisher - one / multiple subscriber)
NIO(New I/O API) uses this, which demultiplexes events(separating single stream into multiple stream) and dispatches them to registered object handlers.