Monday, February 28, 2011

Abstract factory pattern

This pattern is one level of abstraction higher than factory pattern. This means that the abstract factory returns the factory of classes. Like Factory pattern returned one of the several sub-classes, this returns such factory which later will return one of the subclasses.
Let’s understand this pattern with the help of an example.
Suppose we need to get the specification of various parts of a computer based on which work the computer will be used for.
The different parts of computer are, say Monitor, RAM and Processor. The different types of computers are PC, Workstation and Server.
So, here we have an abstract base class Computer.

 

package creational.abstractfactory; 

public abstract class Computer {

public abstract Parts getRAM();
public abstract Parts getProcessor();
public abstract Parts getMonitor();

}




This class, as you can see, has three methods all returning different parts of computer. They all return a method called Parts. The specification of Parts will be different for different types of computers. Let’s have a look at the class Parts.



package creational.abstractfactory; 
public class Parts {

public String specification;
public Parts(String specification) {
this.specification = specification;
}

public String getSpecification() {
return specification;
}

}// End of class




And now lets go to the sub-classes of Computer. They are PC, Workstation and Server.



package creational.abstractfactory; 
public class PC extends Computer {

public Parts getRAM() {
return new Parts("512 MB");
}
public Parts getProcessor() {
return new Parts("Celeron");
}

public Parts getMonitor() {
return new Parts("15 inches");
}
}




package creational.abstractfactory;

public class Workstation extends Computer {

public Parts getRAM() {
return new Parts("1 GB");
}
public Parts getProcessor() {
return new Parts("Intel P 3");
}

public Parts getMonitor() {
return new Parts("19 inches");
}
}




package creational.abstractfactory; 
public class Server extends Computer{

public Parts getRAM() {
return new Parts("4 GB");
}
public Parts getProcessor() {
return new Parts("Intel P 4");
}

public Parts getMonitor() {
return new Parts("17 inches");
}
}




Now let’s have a look at the Abstract factory which returns a factory “Computer”. We call the class ComputerType.

package creational.abstractfactory;
public class ComputerType {
private Computer comp; public static void main(String[] args) {
ComputerType type = new ComputerType(); Computer computer = type.getComputer("Server");
System.out.println("Monitor: "+computer.getMonitor().getSpecification());
System.out.println("RAM: "+computer.getRAM().getSpecification());
System.out.println("Processor: "+computer.getProcessor().getSpecification());
}

public Computer getComputer(String computerType) {
if (computerType.equals("PC"))
comp = new PC();
else if(computerType.equals("Workstation"))
comp = new Workstation();
else if(computerType.equals("Server"))
comp = new Server(); return comp;

}
}




Running this class gives the output as this:
Monitor: 17 inches
RAM: 4 GB
Processor: Intel P 4.

 

When to use Abstract Factory Pattern?
One of the main advantages of Abstract Factory Pattern is that it isolates the concrete classes that are generated. The names of actual implementing classes are not needed to be known at the client side. Because of the isolation, you can change the implementation from one factory to another.

Factory pattern

Factory of what? Of classes. In simple words, if we have a super class and n sub-classes, and based on data provided, we have to return the object of one of the sub-classes, we use a factory pattern.
Let’s take an example to understand this pattern.
The Base class

public class Person {
// name string
public String name;
// gender : M or F
private String gender;

public String getName() {
return name;
}

public String getGender() {
return gender;
}
}// End of class
This is a simple class Person having methods for name and gender. Now, we will have two sub-classes, Male and Female which will print the welcome message on the screen.
Male.java

public class Male extends Person {
public Male(String fullName) {
System.out.println("Hello Mr. "+fullName);
}
}// End of class
Also, the class Female

public class Female extends Person {
public Female(String fullNname) {
System.out.println("Hello Ms. "+fullNname);
}
}// End of class
Now, we have to create a client, or a SalutationFactory which will return the welcome message depending on the data provided.


public class SalutationFactory {
public Person getPerson(String name, String gender) {
if (gender.equals("M"))
return new Male(name);
else if(gender.equals("F"))
return new Female(name);
else return null;
}
}// End of class


This class accepts two arguments from the system at runtime and prints the names.

Running the program:
FactoryPatternDemo.java


public class FactoryPatternDemo{
public static void main(String args[]) {
SalutationFactory factory = new SalutationFactory();
factory.getPerson("Kinshuk", "M");
}
}

The result returned is:

“Hello Mr. Kinshuk”.

When to use a Factory Pattern?


The Factory patterns can be used in following cases:
1. When a class does not know which class of objects it must create.
2. A class specifies its sub-classes to specify which objects to create.
3. In programmer’s language (very raw form), you can use factory pattern where you have to create an object of any one of sub-classes depending on the data provided.




Download source


You can download the source code of this program from here.

Decorator pattern examples

Example 1. Instantiating I/O decorators

FileReader       frdr = new FileReader(filename);
LineNumberReader lrdr = new LineNumberReader(frdr);



The preceding code creates a reader -- lrdr -- that reads from a file and tracks line numbers. Line 1 creates a file reader (frdr), and line 2 adds line-number tracking.

At runtime, decorators forward method calls to the objects they decorate. For example, in the code above, the line number reader, lrdr, forwards method calls to the file reader, frdr. Decorators add functionality either before or after forwarding to the object they decorate; for example, our line number reader tracks the current line number as it reads from an input stream.

Alternatively, of course, you could write Example 1 like this:

LineNumberReader lrdr = new LineNumberReader(new FileReader(filename));



Example 2. Using I/O decorators


try {
LineNumberReader lrdr = new LineNumberReader(new FileReader(filename));
for(String line; (line = lrdr.readLine()) != null;)rticle.txt {
System.out.print(lrdr.getLineNumber() + ":\t" + line);
}
}
catch(java.io.FileNotFoundException fnfx) {
fnfx.printStackTrace();
}
catch(java.io.IOException iox) {
iox.printStackTrace();
}


Decorators represent a powerful alternative to inheritance. Whereas inheritance lets you add functionality to classes at compile time, decorators let you add functionality to objects at runtime.

Classloaders in java

Decorator Pattern

The Decorator Pattern is used for adding additional functionality to a particular object as opposed to a class of objects. It is easy to add functionality to an entire class of objects by subclassing an object, but it is impossible to extend a single object this way. With the Decorator Pattern, you can add functionality to a single object and leave others like it unmodified.
A Decorator, also known as a Wrapper, is an object that has an interface identical to an object that it contains. Any calls that the decorator gets, it relays to the object that it contains, and adds its own functionality along the way, either before or after the call. This gives you a lot of flexibility, since you can change what the decorator does at runtime, as opposed to having the change be static and determined at compile time by subclassing. Since a Decorator complies with the interface that the object that it contains, the Decorator is indistinguishable from the object that it contains.  That is, a Decorator is a concrete instance of the abstract class, and thus is indistinguishable from any other concrete instance, including other decorators.   This can be used to great advantage, as you can recursively nest decorators without any other objects being able to tell the difference, allowing a near infinite amount of customization.

Decorators add the ability to dynamically alter the behavior of an object because a decorator can be added or removed from an object without the client realizing that anything changed.  It is a good idea to use a Decorator in a situation where you want to change the behaviour of an object repeatedly (by adding and subtracting functionality) during runtime.    
The dynamic behavior modification capability also means that decorators are useful for adapting objects to new situations without re-writing the original object's code.
The code for a decorator would something like this:
void doStuff() { 

// any pre-processing code goes here.
   aComponent.doStuff() // delegate to the decoree
// any post-processing code goes here
}



Note that the decorator can opt to not delegate to the decoree, if, for instance, some condition was not met.
A very nice example of decorators is Java's I/O stream implementation.
 

Example


Component


public abstract class Breakfast {

String description = "Unknown Breakfast";

public String getDescription() {
return description;
}
public abstract double cost();
}

Concrete Component

The ConcreteComponent is the object we’re going to dynamically add new behavior to. It extends Component.

public class Dosa extends Breakfast{

public Dosa() {
description = "Dosa";
}

public double cost(){
return 12.50;
}
}

 

Another Component:

 


public class Idli extends Breakfast{

public Idli() {
description = "Idli";
}
public double cost(){
return 10.50;
}
}

Decorator

Each decorator HAS-A (wraps) a component, which means the decorator has an instance variable that holds a reference to a component.
Decorators implement the same interface or abstract class as the component they are going to decorate.


// Decorator
public abstract class Decorator extends Breakfast{

public abstract String getDescription();

}


Concrete Decorator:
The ConcreteDecorator has an instance variable for the thing it decorates (the Component the Decorator wraps).

public class MasalaDosaDecorator extends Decorator{

Breakfast breakfast;

public MasalaDosaDecorator(Breakfast breakfast){
this.breakfast = breakfast;
}

public String getDescription(){
return breakfast.getDescription()+" ,its MasalaDosa";
}

public double cost(){
return breakfast.cost() + 5.50;
}
}


Now have another concrete decorator, say OnionDosaDecorator:



public class OnionDosaDecorator extends Decorator{

Breakfast breakfast;

public OnionDosaDecorator(Breakfast breakfast){
this.breakfast = breakfast;
}

public String getDescription(){
return breakfast.getDescription()+" , its OnionDosa";
}

public double cost(){
return breakfast.cost() + 3.50;
}
}


Decorator Demo : Time to order dosa.


Now its time to have our menu to be served, with main function.



public class BreakfastMenu {

public static void main(String[] args) {

// without adding decorators
Breakfast menu1 = new Dosa();
System.out.println(menu1.getDescription() +" Rs. "+menu1.cost());


//adding decorators
Breakfast menu2 = new MasalaDosaDecorator(new OnionDosaDecorator(new Dosa()));
System.out.println(menu2.getDescription() +" Rs. "+menu2.cost());

Breakfast menu3 = new MasalaDosaDecorator(new Dosa());
System.out.println(menu3.getDescription() +" Rs. "+menu3.cost());
}
}

Decorators can extend the state of the component.
Decorators can add new methods. however new behavior is typically added by doing computation before or after an existing method in the component.
Inheritance is one form of extension, but not necessarily the best way to achieve flexibility in our designs.
In our designs we should allow behavior to be extended without the need to modify existing code.
Composition and delegation can often be used to add new behaviors at runtime.
The Decorator Pattern provides an alternative to subclassing for extending behavior.
The Decorator Pattern involves a set of decorator classes that are used to wrap concrete components.
Decorator classes mirror the type of the components they decorate. (In fact, they are the same type as the components they decorate, either through inheritance or interface implementation.)
Decorators change the behavior of their components by adding new functionality before and/or after (or even in place of) method calls to the component.
You can wrap a component with any number of decorators.
Decorators are typically transparent to the client of the component; that is, unless the client is relying on the component’s concrete type.
Decorators can result in many small objects in our design, and overuse can be complex.
Adapter provides a different interface to its subject.Proxy provides the same interface.Decorator provides an enhanced interface.[GoF, p216]
Adapter changes the object's interface,Decorator enhances an object's responsibilities.Decorator is thus more transparent to the client.As a consequence,Decorator supports recursive composition,which isnt possible with pure Adapters.[GoF, p149]
Composite and Decorator have similar structure diagrams,reflecting the fact that both rely on recursive composition to organize an open-ended number of objects.[GoF, p219]
A Decorator can be viewed as a degenerate Composite with only one component.However a decorator adds additional responsibilities-it isnt intended for object aggregation.[GoF, p184]
Decorator is designed to let you add responsibilites to objects without subclassing.Composite's focus is not an embellishment but on representation.These intents are distinct but complementary.Consequently Composite and Decorator are often used in concert. [GoF, p220]
Decorator lets us change the skin of an object.Strategy lets us change the guts.[GoF, p184]
Decorator and Proxy have diff purposes but similar structures.Both describe how to provide a level of indirection to another object,and the implementations keep a reference to the object to which they forward requests.[GoF, p220]

Disadvantage



Only disadvantage is code maintenance can be a problem as it provides the system with a lot of similar looking small objects(each decorator).

Problems in java.util.Observable

Consider Observable pattern.

The way its implemented in java is full of flaws.

1. Observable is a class, not an interface, and worse, it doesn’t even implement an interface. Unfortunately, the java.util.Observable implementation has a number of problems that limit its usefulness and reuse. That’s not to say it doesn’t provide some utility, but there are some large potholes to watch out for. So from design point of view its bad in 2 ways:

   A) Because Observable is a class, you have to subclass it. That means you can’t add on the Observable behavior to an existing class that already extends another superclass. This limits its reuse potential (and isn’t that why we are using patterns in the first place?).
   B) Because there isn’t an Observable interface, you can’t even create your own implementation that plays well with Java’s built-in Observer API. Nor do you have the option of swapping out the java.util implementation for another (say, a new, multithreaded implementation).

2. Observable may serve your needs if you can extend java.util.Observable. On the other hand, you may need to roll your own implementation as we did at the beginning of the chapter. In either case, you know the Observer Pattern well and you’re in a good position to work with any API that makes use of the pattern.

3. If you look at the Observable API, the setChanged() method is protected. So what? Well, this means you can’t call setChanged() unless you’ve subclassed Observable. This means you can’t even create an instance of the Observable class and compose it with your own objects, you have to subclass. The design violates a second design principle here…favor composition over inheritance.

Strategy pattern

The Strategy Design Pattern basically consists of decoupling an algorithm from its host, and encapsulating the algorithm into a separate class. More simply put, an object and its behaviour are separated and put into two different classes. This allows you to switch the algorithm that you are using at any time.

There are several advantages to doing this. First, if you have several different behaviours that you want an object to perform, it is much simpler to keep track of them if each behaviour is a separate class, and not buried in the body of some method. Should you ever want to add, remove, or change any of the behaviours, it is a much simpler task, since each one is its own class. Each such behaviour or algorithm encapsulated into its own class is called a Strategy.

When you have several objects that are basically the same, and differ only in their behaviour, it is a good idea to make use of the Strategy Pattern.. Using Strategies, you can reduce these several objects to one class that uses several Strategies. The use of strategies also provides a nice alternative to subclassing an object to achieve different behaviours. When you subclass an object to change its behaviour, that behaviour that it executes is static. If you wanted to change what it does, you'd have to create a new instance of a different subclass and replace that object with it. With Strategies, however, all you need to do is switch the object's strategy, and it will immediately change how it behaves. Using Strategies also eliminates the need for many conditional statements. When you have several behaviours together in one class, it is difficult to choose among them without resorting to conditional statements. If you use Strategies you won't need to check for anything, since whatever the current strategy is just executes without asking questions.

strategy_implementation_-_uml_class_diagram

So context has strategy reference and it changes it strategy whenever needed, by using it setters for that strategy reference.

Example

Strategy.java
Suppose we are into making cake, and there are few strategies of making cake.

package com.cakes;

public interface Strategy {

boolean checkTemperature(int temperatureInF);

}


Strategy1


The HikeStrategy class is a concrete strategy class that implements the Strategy interface. The checkTemperature method is implemented so that if the temperature is between 50 and 90, it returns true. Otherwise it returns false.

HikeStrategy.java

package com.cakes;

public class HikeStrategy implements Strategy {

@Override
public boolean checkTemperature(int temperatureInF) {
if ((temperatureInF >= 50) && (temperatureInF <= 90)) {
return true;
} else {
return false;
}
}

}



Strategy 2 :


The SkiStrategy implements the Strategy interface. If the temperature is 32 or less, the checkTemperature method returns true. Otherwise it returns false.

SkiStrategy.java

package com.cakes;

public class SkiStrategy implements Strategy {

@Override
public boolean checkTemperature(int temperatureInF) {
if (temperatureInF <= 32) {
return true;
} else {
return false;
}
}

}



Context


The Context class contains a temperature and a reference to a Strategy. The Strategy can be changed, resulting in different behavior that operates on the same data in the Context. The result of this can be obtained from the Context via the getResult() method.

package com.cakes;

public class Context {

int temperatureInF;
Strategy strategy;

public Context(int temperatureInF, Strategy strategy) {
this.temperatureInF = temperatureInF;
this.strategy = strategy;
}

public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}

public int getTemperatureInF() {
return temperatureInF;
}

public boolean getResult() {
return strategy.checkTemperature(temperatureInF);
}

}


Demo of pattern


The Demo class creates a Context object with a temperature of 60 and with a SkiStrategy. It displays the temperature from the context and whether that temperature is OK for skiing. After that, it sets the Strategy in the Context to HikeStrategy. It then displays the temperature from the context and whether that temperature is OK for hiking.


Demo.java

package com.cakes;

public class Demo {

public static void main(String[] args) {

int temperatureInF = 60;

Strategy skiStrategy = new SkiStrategy();
Context context = new Context(temperatureInF, skiStrategy);

System.out.println("Is the temperature (" + context.getTemperatureInF() + "F) good for skiing? " + context.getResult());

Strategy hikeStrategy = new HikeStrategy();
context.setStrategy(hikeStrategy);

System.out.println("Is the temperature (" + context.getTemperatureInF() + "F) good for hiking? " + context.getResult());

}

}



Console Output
Is the temperature (60F) good for skiing? false
Is the temperature (60F) good for hiking? true

Sunday, February 27, 2011

Polyglot programming : Definition

In computing, a polyglot is a computer program or script written in a valid form of multiple programming languages, which performs the same operations or output independent of the programming language used to compile or interpret it.
Generally polyglots are written in a combination of C (which allows redefinition of tokens with a preprocessor) and a scripting language such as Lisp, Perl or sh.

So the application using polyglot have access to low level resources provided by lisp and also scripting gives it edge to use these resources in better way.

Java memory model

http://www.cs.umd.edu/users/pugh/java/memoryModel/
This is v.good material to follow java memory model.

Double Checked Locking And Java Singletons

Consider a singleton class:
class FooSingleton { 
private String name;

private FooSingleton instance;

private FooSingleton(String name_)
{
name=name_;
}
public FooSingleton getInstance() {
if (instance== null)
instance= new FooSingleton ();
return FooSingleton ;
}
// other functions and members...
}
The Singleton pattern is used when we want to ensure that there is only one instance of a class per something. In most cases, the something is 'JVM - Classloader' combination. So, in such cases we want to ensure that there is only one instance of the Singleton class in the JVM-Classloader. But we are not restricted to this. We may need only one instance of the Singleton per Session, or per Request, or per anything else that makes sense in the software you are making.

It is clear that we want to control the instantiation process of the Singleton class. To do this, the first thing we do as shown in the example is to make the constructor private. With the constructor private, no other class can create an instance of this class. OK, so how will we create any instance of this class? We provide a public static method called getInstance() which will return an instance of this class. We will also use a private static field called instance to hold the one and only instance of this class. Since we control the getInstance() method, every time it is invoked we will return instance. The first time however, instance will not be initialized, so we put a null check in getInstance() and instantiate instance if it has not already been instantiated. Hence forth we will always return a reference to instance. This way we ensure that only one instance of our Singleton will be ever created (the one we save in the field called instance).

Is This A Safe Singleton?
Answer : No, Singleton is not thread-safe.

Explanation
Consider getInstance() method. Imagine that a thread T1 invokes getInstance(). If an instance of the Singleton has not been created till now, then instance will be null, and T1 will enter the if block. Now imagine that T1 gets pre-empted, and thread T2 also calls getInstance(). Since T1 got pre-empted before it got a chance to create instance, the reference in instance is still null. So T2 will also enter the if block. Now if T2 does not get pre-empted then it will go ahead all the way where it will create an instance of Singleton, and probably even use it. Now when T1 is resumed, unfortunately it does not know that the Singleton has already been created, since it has already gone past the null check. T1 will also happily create an instance of our Singleton, thus breaking the Singleton pattern. We have 2 instances of the Singleton which is simply not allowed.

Making Singleton threadsafe

Approach1 
Using synchronized, we can make our singleton class threadsafe.
eg.
public static synchronized FooSingleton getInstance(){}

Making a method synchronized is expensive. A thread executing a synchronized method must acquire a monitor before it can invoke the method, and release the monitor after executing the method. This takes time and CPU cycles. In early JVM's (I have read somewhere), the time to invoke (not execute) a synchronized method was as much as 100x the time taken to invoke a non synchronized method. I think this was improved in later JVM's where it was about 15x. I recently did a quick test on JDK 1.6, and the number I got was 2x. Regardless of how much slower it is, it is definitely slower, and programmers always want to make their code fast.

Approach 2 - Use Double Checked Locking
class FooSingleton { 
private String name;

private FooSingleton instance;

private FooSingleton(String name_)
{
name=name_;
}
public synchronized FooSingleton getInstance() {
if(intance==null){
synchronized(FooSingleton.class){
if (instance== null)
instance= new FooSingleton ();
}
}
return FooSingleton ;
}
// other functions and members...
 
So instead of using synchronized for getInstance, we use it for class level using :  synchronized(FooSingleton.class)
 
What we really should have done, is only synchronize the code which  instantiates the Singleton, and not the entire method. That way we incur  the expense of the synchronized block only once, when the Singleton  needs to be created, and all subsequent times (instance == null) will  always be false, and the instance will be returned to the calling code.   We put a second check inside the synchronized block, because it is  possible that a thread could get pre-empted just after the first null  check, but before it enters the synchronized block. In such a case, if  another thread enters this method, and goes all the way to creating the  instance then the first thread will not know of it and will create a  second instance. To prevent this, we put another check in the  synchronized block.

Will It Work?
Answer is no. But why?
There are two reasons why it does not work. The compiler as well as the processor (as well as the JVM) may reorder instructions if they feel it might be more optimal. Off course they cannot randomly reorder instructions but they could if they can prove that the reordering will maintain as-if-serial semantics. However, this is not the only reason. On a multi-processor system, each processor has it's own memory cache. The cache is not always synchronized with main memory immediately. This can cause a write to a memory location to happen in the local cache, which will not be visible to other threads which could be running on other processors. Even if the writing thread does flush it's local cache, it is still possible that another thread which reads that value, may not have pulled in most recent values from the main memory into it's local cache. This can cause a situation very similar to reordering where the effect of a write is not visible to another thread that is reading that variable's value.

Is  statement below is atomic statement -- you might think that the statement below is an atomic statement.
instance = new FooSingleton ();
But that is not the case. For the sake of simplicity this slide shows the statement above broken into 2 operations. In the first part, an instance of the class is constructed, and in the second part a reference to that instance is assigned to the variable instance.

Compiler Reordering:
Now what if the compiler reorders the instructions in such a way that the field instance is assigned an uninitialized block of memory (created for the class FooSingleton ), and then the constructor of FooSingleton is invoked in the second step.

Compiler Reordering Pseudocode:
This slides shows pseudocode to understand the effect of compiler reordering on the double checked locking code. The code in the synchronzied block which instantiates our Singleton is broken into two steps: assignment, and initialization, where the assignment happens before the initialization.

Now imagine thread T1 enters the getInstance() method, enters the synchronized block and executes the statement which assigns the block of memory allocated for FooSingleton to the variable called instance. If T1 gets preempted and thread T2 enters getInstance() then T2 may see a non null value for instance. Thus T2 will actually be returned an initialized object of FooSingleton . This could cause all sorts of bugs in the software.

So in the first problem described a few slides back, we ran into the issue of having multiple instances of our Singleton, which we attempted to fix with the double checked locking idiom. However, this introduced the issue where a thread might be given a reference to an uninitialized instance of the Singleton.

Can We Prevent reordering:
Programmers never give up :-) When an even smarter programmer was explained this problem, he remarked "so let us prevent reordering and our problem will be solved !". Ok let's try that, but how do we prevent reordering? Well there is something called a memory barrier, which may help us. Instructions cannot be reordered across memory barriers (although they may be reordered within a memory barrier). Let's see if we can introduce memory barriers to prevent the reordering that's been giving us such a hard time till now.

Memory Barrier:
A memory barrier is a low level (at the level of the processor) construct which is used to create a fence around instructions. Instructions which are fenced inside a memory barrier cannot be moved out of the fence, and memory caches are also synched with main memory when a memory barrier is encountered.

slide 15 (Memory Barrier):
Now consider the instruction set :
instr1
instr2
instr3
instr4
instr5
Instructions instr1 and instr5 (in red) are not allowed to move any bottom or down, but instructions in green are allowed to reorder.
Notice that instructions (instr2, instr3, & instr3) are fenced with the memory barrier. Because of the semantics of a memory barrier these instructions can never be moved out of the barrier, but they may be re-ordered within the memory barrier. We can also see when the memory barrier is entered the local processor cache is invalidated and latest values are read from the main memory, and when the memory barrier is exited then the local cached is flushed and the main memory is updated with the latest values.

The synchronized keyword in Java creates a memory barrier
Because memory barrier is a low level construct, there is no way to explicitly create one in a high level language like Java. However, the synchronized keyword in Java implicitly creates a memory barrier. Before I read this, I had no clue that synchronization in Java is anything more than a mutex. But I read somewhere that when a monitor is obtained an memory barrier is also created and when a monitor is released the memory barrier ends (this is my understanding, please correct me if this is wrong).

Double Checked Locking With Memory Barrier:
public synchronized FooSingleton getInstance() {
if(intance==null)
{
FooSingleton tempInstance;
synchronized(FooSingleton.class)
{
if (tempInstance== null)
{
tempInstance= new FooSingleton ();
}
instance=tempInstance;
}
}
return instance;
}
The fact that assignment and construction of our Singleton could be reordered created the issue of potentially having an uninitialized Singleton. We want to ensure that the reordering does not happen. For that let us separate the construction and assignment with a memory barrier and put the assignment after the construction. We do this with 2 synchronized blocks and a temporary variable. In the inner synchronized block we will initialize the Singleton and assign it to a temporary variable. We don't care if this is reordered, because the class variable instance will still be null which will prevent another thread from getting an initialized instance of the Singleton. Then we assign the reference to the temporary variable to the class variable instance. This happens outside the memory barrier. So by employing a memory barrier we are hoping to maintain program order in the execution of instructions. Again a very smart solution, but unfortunately this does not work either.

Monitor Exit Semantics:
The semantics of monitor exit specify that everything that happened before the monitor exit should happen before it, which means that nothing from the inner synchronized block (where we instantiate the Singleton) will be moved out of the inner synchronized block, however, it does not mean that something will not be moved from outside of the block to within it.

instr2
instr3
instr4
So consider  inst2 and inst3 are within the memory barrier. Neither of them will be moved out of the block, but inst4 which is out of the memory barrier may be moved in the barrier.

Double Checked Locking With Memory Barrier
So consider above code(getInstance method) with a potential reordering. With the statement instance = tempInstance inside the memory barrier it could be further reordered to the point before the actual construction of the Singleton, bringing us back to the same problem.

OK So What The Hell Will Work ?:
Alright enough of playing around... not I am getting a bit edgy.... just tell me what the hell is going to work. Is this what you are saying to yourself? Java has a special modifier called volatile. We can use these fields to help us with the Singleton.

Semantics of volatile:
The volatile modifier is used in Java to communicate state changes between threads. This slide explains the semantics of volatile with an illustration.


Double Checked Locking With Volatile:
So now our solution comes to:
private static volatile FooSingleton instance;
This elimitaes the problem of seeing an uninitialized Singleton object.

Singleton With Static Initializer:
After doing all these coding gymnastics, we show a solution which is probably the simplest solution for creating a thread safe Singleton. Instead of instantiating the Singleton in getInstance(), we use a static initializer, which will instantiate the Singleton when the class is loaded. Java semantics ensure us that all static fields of a class will be completely initialized before the class is available for use. This means that the field instance will be properly initialized before anyone makes use of the class to get an instance of the Singleton.

Singleton With Static Initializer:
In this slide we understand the pros and cons of using a static initializer. Even though using a static initializer is the simplest solution, it is possible that everything the Singleton needs to initialize itself may not be available when the class is loaded (which causes the static initializer to be invoked). It is also possible that the Singleton may be eagerly loaded, which may result in greater loading time for our application, something that may be undesirable if instantiating the Singleton is an expensive operation.

Summary:
  • The compiler as well as the processor can reorder instructions under certain conditions
  • Even if the instructions are not re-ordered, a thread may still see a stale value of a field due to memory caching
  • Synchronization creates an implicit memory barrier
  • Code cannot be moved from within the memory barrier to outside of it
  • Code MAY be moved from outside a memory barrier to within it
  • Volatile fields cannot be re-ordered with respect to other volatile fields, and are very difficult to reorder in respect to non volatile fields 
  • A read to a volatile field invalidates the processor cache and fetches values from main memory
  • A write to a volatile field flushes the value to main memory
  • These semantics are all part of the Java memory model
Resources:
Links to some very good and relevant articles, including my favorite article by Bill Pugh.
One more thing before signing of - many people (here and here, but someone also disagrees) consider Singletons to be evil...

Observer and Observable pattern in Java

Definition
Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
The observer pattern (a subset of the publish/subscribe pattern) is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.
The Observer pattern allows one object (the observer) to watch another (the subject). The Observer pattern allows the subject and observer to form a publish-subscribe relationship. Through the Observer pattern, observers can register to receive events from the subject. When the subject needs to inform its observers of an event, it simply sends the event to each observer.
For example, you might have a spreadsheet that has an underlying data model. Whenever the data model changes, the spreadsheet will need to update the spreadsheet screen and an embedded graph. In this example, the subject is the data model and the observers are the screen and graph. When the observers receive notification that the model has changes, they can update themselves.
 
Lets have 2 interfaces:
public interface Subject {
public void addObserver( Observer o );
public void removeObserver( Observer o );
}
public interface Observer {
public void update( Subject o );
}

So concrete classes implementing these interface must have these methods. In the subject class, we will call update passing reference of the Observer class and call update accordingly.

So creating the subject….say it is an integer bag…which can be modified and it has to notify its observer when some events happen. IntegerDataBag which implements Subject holds onto Integer instances. The IntegerDataBag also allows Observers to add and remove themselves.
import java.util.ArrayList;
import java.util.Iterator;
public class IntegerDataBag implements Subject {
private ArrayList list = new ArrayList(); //list of observables, integer here
private ArrayList observers = new ArrayList();//list of observers
public void add( Integer i ) {
list.add( i ); //when adding int to int bag, notify all
notifyObservers();
}
public Iterator iterator() {
return list.iterator();
}
public Integer remove( int index ) {
if( index &lt; list.size() ) {
Integer i = (Integer) list.remove( index );
notifyObservers();//when removing int to int bag, notify all
return i;
}
return null;
}
public void addObserver( Observer o ) {
observers.add( o );
}
public void removeObserver( Observer o ) {
observers.remove( o );
}
private void notifyObservers() {
// loop through and notify each observer
Iterator i = observers.iterator();
while( i.hasNext() ) {
Observer o = ( Observer ) i.next();
o.update( this );//Calls update method of Observer as notification
}
}
}

Consider these two implementations of Observer -- IntegerAdder and IntegerPrinter:

Observer1
import java.util.Iterator;
public class IntegerAdder implements Observer {
private IntegerDataBag bag; //Observable or subject
public IntegerAdder( IntegerDataBag bag ) {
this.bag = bag;
bag.addObserver( this );//Observer1 adds itself to observable list
}
public void update( Subject o ) {
if( o == bag ) {
System.out.println( "The contents of the IntegerDataBag have changed." );
int counter = 0;
Iterator i = bag.iterator();
while( i.hasNext() ) {
Integer integer = ( Integer ) i.next();
counter+=integer.intValue();
}
System.out.println( "The new sum of the integers is: " + counter );
}
}
}

Observer2
import java.util.Iterator;
public class IntegerPrinter implements Observer {
private IntegerDataBag bag;
public IntegerPrinter( IntegerDataBag bag ) {
this.bag = bag;
bag.addObserver( this );//Observer1 adds itself to observable list
}
public void update( Subject o ) {
if( o == bag ) {
System.out.println( "The contents of the IntegerDataBag have changed." );
System.out.println( "The new contents of the IntegerDataBag contains:" );
Iterator i = bag.iterator();
while( i.hasNext() ) {
System.out.println( i.next() );
}
}
}
}

IntegerAdder and IntegerPrinter add themselves to the integer bag as observers. When an IntegerAdder receives an update, it sums up the Integer values held in the bag and displays them. Likewise, when IntegerPrinter receives an update, it prints out the Integers held in the bag.

Here is a simple main() that exercises these classes:
public class Driver {
public static void main( String [] args ) {
Integer i1 = new Integer( 1 ); Integer i2 = new Integer( 2 );
Integer i3 = new Integer( 3 ); Integer i4 = new Integer( 4 );
Integer i5 = new Integer( 5 ); Integer i6 = new Integer( 6 );
Integer i7 = new Integer( 7 ); Integer i8 = new Integer( 8 );
Integer i9 = new Integer( 9 );
IntegerDataBag bag = new IntegerDataBag();
bag.add( i1 ); bag.add( i2 ); bag.add( i3 ); bag.add( i4 );
bag.add( i5 ); bag.add( i6 ); bag.add( i7 ); bag.add( i8 );
IntegerAdder adder = new IntegerAdder( bag );
IntegerPrinter printer = new IntegerPrinter( bag );
// adder and printer add themselves to the bag
System.out.println( "About to add another integer to the bag:" );
bag.add( i9 );
System.out.println("");
System.out.println("About to remove an integer from the bag:");
bag.remove( 0 );
}
}
04-qa-0525-observer1

The IntegerDataBag/IntegerAdder/IntegerPrinter is a simple example of the Observer pattern. Within Java itself there are a number of examples of the Observer pattern: the AWT/Swing event model, as well as the java.util.Observer and java.util.Observable interfaces serve as examples.

So the picture goes like this:

One-to-many relationship
The subject and observers define the one-to-many relationship. The observers are dependent on the subject such that when the subject’s state changes, the observers get notified.  Depending on the style of notification, the observer may also be updated with new values. With the Observer pattern, the Subject is the object that contains the state and controls it. So, there is ONE subject with state. The observers, on the other hand, use the state, even if they don’t own it. There are many observers and they rely on the Subject to tell them when its state changes.
So there is a relationship between the ONE Subject to the MANY Observers.



Extending books to loanable and reference books

class LoanBook extends Book
{
public LoanBook (String t, String a, int c1, int c2, float p)
{
super(t,a,c1,c2,p);
}

public boolean canLoan()
{
return true;
}

public String details ()
{
return "Loan: "+super.details();
}

public String toString()
{
return "loan: "+super.toString();
}
}

class ReferenceBook extends Book
{
public ReferenceBook (String t, String a, int c1, int c2, float p)
{
super(t,a,c1,c2,p);
}

public boolean canLoan()
{
return false;
}

public String details ()
{
return "Reference: "+super.details();
}

public String toString()
{
return "Ref: "+super.toString();
}
}



class Loan
{
Book book;
Person person;
Date date = new Date();

public Loan (Book b, Person p)
{
book = b;
person = p;
}

public String details ()
{
return book.details()+" loaned on "+date+" to "+person.details();
}

public String toString()
{
return "book "+book+" -&gt; person"+person+" @date "+date;
}
}

public class Library
{
public static void main(String[] args)
{
Book b1 = new LoanBook ("Java I/O Programming","E.R.Harrold",123,45,18.99F);
Book b2 = new LoanBook ("Java in a Nutshell","D.Flanagan",123,25,12.99F);
Book b3 = new ReferenceBook ("The Java CLass Libraries","P.Chan &amp; R.Lee",2123,10,35.00F);

System.out.println("Books");
System.out.println(b1);
System.out.println(b2);
System.out.println(b3);
System.out.println("");

System.out.println("People:");
Person james = new Person ("James Gosling");
System.out.println(james);
System.out.println("");

Loan l1 = makeLoan(james, b1);
Loan l2 = makeLoan(james, b2);
Loan l3 = makeLoan(james, b3);
}

private static Loan makeLoan(Person p, Book b)
{
Loan l=null;
if (b.canLoan())
{
l = new Loan(b,p);
System.out.println(l.details());
}
else
System.out.println("Cannot loan "+b.details()+" to "+p.details());
System.out.println("");
return l;
}


}

Making library of books

To have library we can have 2 components for sure:
1. Books
2. Person borrowing that books

So we need a person class
class Person
{
String name;
public Person (String n)
{
name = n;
}

public String details ()
{
return name;
}

public String toString()
{
return "name &lt;"+name+"&gt;";
}
}
 
Person must take membership from library...so something has to be added to above
class Membership
{
public boolean canLoan(int onLoan)
{
return false;
}
}

class JuniorMember extends Membership
{
public boolean canLoan(int onLoan)
{
return onLoan&lt;1;
}
public String toString()
{
return "Junior";
}
}

class StandardMember extends Membership
{
public boolean canLoan(int onLoan)
{
return onLoan&lt;6;
}
public String toString()
{
return "Standard";
}
}

class OAPMember extends Membership
{
public boolean canLoan(int onLoan)
{
Calendar now = Calendar.getInstance();
int day = now.get(Calendar.DAY_OF_WEEK);
//if (day==Calendar.SATURDAY || day==Calendar.SUNDAY)
if (day == Calendar.THURSDAY)
return false;
return true;
}
public String toString()
{
return "OAP";
}
}
We have to add how many books person borrowed...so we have to add following function:
 So now person class become:
public class Person
{
String name;
Membership mem;
int books;
public Person (String n, Membership member)
{
name = n;
mem = member;
}

public boolean borrow(Book b)
{
if (b.canLoan() &amp;&amp; mem.canLoan(books))
{
books++;
return true;
}
return false;
}

public String details ()
{
return name+":"+mem;
}

public String toString()
{
return "name &lt;"+name+"&gt; "+mem;
}
}

General way of making class : Book

class Book
{
String title;
String author;
float price;
int cat, subCat;

public Book (String t, String a, int c1, int c2, float p)
{
title = t;
author = a;
price = p;
cat = c1;
subCat = c2;
}

public String details ()
{
return title+", "+author+" Category "+cat+"."+subCat+" value $"+price;
}

public String toString()
{
return "Title &lt;"+title+"&gt; Author &lt;"+author+"&gt; cat:"+cat+" subCat:"+subCat+" price:"+price;
}
}

Singleton pattern

Step 1: Provide a default Private constructor
public class Singleton {

// Note that the constructor is private
private Singleton() {
// Optional Code
}
}
Step 2: Create a Static Method for getting the reference to the Singleton Object
public class Singleton {

private static Singleton instance;
// Note that the constructor is private
private Singleton() {
// Optional Code
}
public static Singleton getInstance() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
}
We write a public static getter or access method to get the instance of the Singleton Object at runtime. First time the object is created inside this method as it is null. Subsequent calls to this method returns the same object created as the object is globally declared (private) and the hence the same referenced object is returned.

Step 3: Make the Access method Synchronized to prevent Thread Problems.
public static synchronized Singleton getInstance()
It could happen that the access method may be called twice from 2 different classes at the same time and hence more than one object being created. This could violate the design patter principle. In order to prevent the simultaneous invocation of the getter method by 2 threads or classes simultaneously we add the synchronized keyword to the method declaration

Step 4: Override the Object clone method to prevent cloning

We can still be able to create a copy of the Object by cloning it using the Object’s clone method. This can be done as shown below
SingletonObjectDemo clonedObject = (SingletonObjectDemo) obj.clone();
This again violates the Singleton Design Pattern’s objective. So to deal with this we need to override the Object’s clone method which throws a CloneNotSupportedException exception.

public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
The below program shows the final Implementation of Singleton Design Pattern in java, by using all the 4 steps mentioned above.
class Singleton {

private static Singleton singletonObject;
/** A private Constructor prevents any other class from instantiating. */
private Singleton() {
// Optional Code
}
public static synchronized Singleton getInstance() {
if (singletonObject == null) {
singletonObject = new Singleton();
}
return singletonObject;
}
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
}

public class SingletonObjectDemo {

public static void main(String args[]) {
// Singleton obj = new Singleton(); //Compilation error not allowed 
Singleton obj = Singleton.getInstance();
// Your Business Logic
System.out.println("Singleton object obtained");
}
}



Another approach
We don’t need to do a lazy initialization of the instance object or to check for null in the get method. We can also make the singleton class final to avoid sub classing that may cause other problems.
public class SingletonClass {

private static Singleton ourInstance = new Singleton();
public static SingletonClass getInstance() {
return singletonObj;
}
private SingletonClass() {
}
}
In Summary, the job of the Singleton class is to enforce the existence of a maximum of one object of the same type at any given time. Depending on your implementation, your class and all of its data might be garbage collected. Hence we must ensure that at any point there must be a live reference to the class when the application is running.

But still there are some issues left.
Protected vs Private Constructor 
protected Singleton() {
// ...
}
The constructor could be made private to prevent others from instantiating 
this class. But this would also make it impossible to create instances of 
Singleton subclasses.
 

CXF hello world tutorial

This example shows how to make cxf web service.

Get the bean ready:
package com.company.auth.bean;

import java.io.Serializable;
import java.util.Set;

public class Employee implements Serializable {

    private static final long serialVersionUID = 1L;
    private String gid;
    private String lastName;
    private String firstName;
    private Set<String> privileges;

    public Employee() {}

    public Set<String> getPrivileges() {
        return privileges;
    }

    public void setPrivileges(Set<String> privileges) {
        this.privileges = privileges;
    }    

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getGid() {
        return gid;
    }

    public void setGid(String gid) {
        this.gid = gid;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public boolean isUserInRole(String role) {
        if(privileges == null) { return false; }
        else { return privileges.contains(role); }
    }

}

First off, you need to download Apache CXF and drop the necessary .jars in your WEB-INF/lib directory:
aopalliance-1.0.jar
commons-logging-1.1.jar
cxf-2.0-incubator.jar
geronimo-activation_1.1_spec-1.0-M1.jar (or Sun’s Activation jar)
geronimo-annotation_1.0_spec-1.1.jar (JSR 250)
geronimo-javamail_1.4_spec-1.0-M1.jar (or Sun’s JavaMail jar)
geronimo-servlet_2.5_spec-1.1-M1.jar (or Sun’s Servlet jar)
geronimo-ws-metadata_2.0_spec-1.1.1.jar (JSR 181)
jaxb-api-2.0.jar
jaxb-impl-2.0.5.jar
jaxws-api-2.0.jar
jetty-6.1.5.jar
jetty-util-6.1.5.jar
neethi-2.0.jar
saaj-api-1.3.jar
saaj-impl-1.3.jar
spring-core-2.0.4.jar
spring-beans-2.0.4.jar
spring-context-2.0.4.jar
spring-web-2.0.4.jar
stax-api-1.0.1.jar
wsdl4j-1.6.1.jar
wstx-asl-3.2.1.jar
XmlSchema-1.2.jar
xml-resolver-1.2.jar

The first thing which needed to be done was to create the service interface. The service interface defines which methods the web service client will be able to call. It’s pretty standard Java with just two JWS (Java Web Service) annotations thrown in:

package com.company.auth.service;

import javax.jws.WebService;
import javax.jws.WebParam;
import com.company.auth.bean.Employee;

@WebService
public interface AuthService {
    Employee getEmployee(@WebParam(name="gid") String gid);
}

The @WebParam annotation is in fact optional, but highly recommended since it will make like easier for the end consumers of your service. Without it, your parameter would be named arg0 making it less clear what parameters your service actually takes.

Implementing the actual service comes next:

package com.company.auth.service;

import javax.jws.WebService;

import com.company.auth.bean.Employee;
import com.company.auth.dao.EmployeeDAO;

@WebService(endpointInterface = "com.company.auth.service.AuthService", serviceName = "corporateAuthService")
public class AuthServiceImpl implements AuthService {

    public Employee getEmployee(String gid) {
        EmployeeDAO dao = new EmployeeDAO();
        return dao.getEmployee(gid);
    }

}

I then had to tell Spring (which is used by CXF) where to find my Java classes. I created the following cxf.xml file inside my package directory (com/company/auth/service):

<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:jaxws="http://cxf.apache.org/jaxws"
      xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://cxf.apache.org/jaxws

                     http://cxf.apache.org/schemas/jaxws.xsd">

  <import resource="classpath:META-INF/cxf/cxf.xml" />
  <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml"/>
  <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
  <jaxws:endpoint id="auth"
                  implementor="com.company.auth.service.AuthServiceImpl"
                  address="/cxfAuth"/>
</beans>

Finally, I updated my WEB-INF/web.xml file to let CXF know where my cxf.xml file was and define the CXF servlet:
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
  <display-name>Auth Manager</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:com/company/auth/service/cxf.xml</param-value>
  </context-param>
  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
  <servlet>
    <servlet-name>CXFServlet</servlet-name>
    <servlet-class>
        org.apache.cxf.transport.servlet.CXFServlet
    </servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CXFServlet</servlet-name>
    <url-pattern>/services/*</url-pattern>
  </servlet-mapping>
</web-app>

The final step is to build the client. This was very easy when compared to getting the server up and running because I was able to simply swipe the code from the Apache CXF documentation. So, without further ado:

package com.company.auth.client;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import com.company.auth.bean.Employee;
import com.company.auth.service.AuthService;

public final class Client {

    private Client() {
    } 

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

        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

        factory.getInInterceptors().add(new LoggingInInterceptor());
        factory.getOutInterceptors().add(new LoggingOutInterceptor());
        factory.setServiceClass(AuthService.class);
        factory.setAddress("http://localhost:7001/authManager/services/cxfAuth");
        AuthService client = (AuthService) factory.create();

        Employee employee = client.getEmployee("0223938");
        System.out.println("Server said: " + employee.getLastName() + ", " + employee.getFirstName());
        System.exit(0);

    }

}

Chitika