Monday, August 16, 2010

Java References

We all have known the concept of a "reference" in Java. It is one of the basics of the language. Any object in java is reached by a reference. Reference is the lifeline of an object; without the reference there is no chance for an object to live after a visit by the garbage collector. The references that we create are generally called as 'strong references'. It makes an object persist in the java heap(memory which holds all java objects in a JVM) as long as the reference is reachable even though the object is not used for the rest of the code. Most of the applications now use a lot of objects which include multimedia and other memory consuming objects. It would be really nice if we could say to the VM that the big picture that it is showing can be removed from memory to make room for a more important document instead of crashing by throwing an OutOfMemoryError. As of Java 2(Yes! Its been around here for a while before I came to know of it), we have three additional reference types that cater our needs regarding the object lifetime. They are a way to interact with the Garbage Collector.

They are:
1. SoftReference,
2. WeakReference,
3. PhantomReference.
from the package java.lang.ref ordered by their strictness of the object hold.

A Softly Referenced object cannot have a strong reference but a SoftReference pointing at it.

A Weakly Referenced object cannot have a strong reference, Soft reference but a WeakReference pointing at it.

A Phantomly Referenced object cannot have a strong reference, soft reference, weak reference but a PhantomReference pointing at it.

We always should use the get() method of the Reference class to get the reference of the object that it points to.

SoftReference:

A softly referenced object stays in memory as long as the garbage collector feels there is enough memory to keep it alive (Note that the garbage collector may collect this object even if there is enough memory). A sample code is given below:

Date d = new Date();
SoftReference sr = new SoftReference(d);
d = null; //remove the strong reference
System.out.println(sr.get()); //prints the date provided no GC is run after line 2
System.gc();
System.out.println(sr.get()); //may or may not print the date


This makes the soft reference an ideal candidate to store objects like pictures alive as long as memory permits.

WeakReference:

A Weakly referenced object is garbage collected as soon as the GC finds it. A sample code is given below:

Date d = new Date();
WeakReference sr = new WeakReference(d);
d = null; //remove the strong reference
System.out.println(sr.get()); //prints the date provided no GC is run after line 2
System.gc();
System.out.println(sr.get()); //Will print only null


A weak reference is mostly used for mappings. In other words, the weak reference acts as a key to a value in a map structure. Usually the key is a kind of object that has a small lifetime so that it is acceptable that it can be Collected by GC as soon as possible. So collecting the key is ok. How do we remove the value that this key is pointing to? We have a ReferenceQueue data structure which will help us keep track of all the references of GC collected objects. We will see about this queue at the end. Just keep in mind that this queue will contain the references.

PhantomReference:

This has the simplest definition of all the references but the most annoying one for me to understand. I took a lot of time to understand its use and i could finally get some help. If I am not to the point here, you are welcome to correct me :-)
When an object is referred by a phantom reference it means that there is no way that we could get a reference to the original object(Except by using Reflection). The get() method of the PhantomReference class always returns null even though the original object is still around. This is designed to avoid the user from creating a strong reference to the referred object. With the other two references it is possible to create a strong reference to the referent. But with a PhantomReference you can't. That is because the finalization on that object is already done and you are not supposed do any operations further on that object. Then whats the purpose of such an object? The only purpose is to know, when an object is ready for removal. At that point of time, the reference is added to the ReferenceQueue. Huh! Why would you even want to know that? Because when the referent becomes phantomly reachable, you may subsequently want to perform post-finalization cleanup tasks that relate to the referent but do not involve the referent -- because there is no way for the program to access the referent. The user has to manually call clear() on the reference to clear the referent. I know thats a lot of 'becauses'. But I hope you understand the concept. Leave me a comment if you have any questions or if I have to put it in a different manner.

A sample code is given below:

Date d = new Date();
PhantomReference sr = new PhantomReference(d);
d = null; //remove the strong reference
System.out.println(sr.get()); //null, always


ReferenceQueue:

The reference queue is a data structure in which the GC puts the reference when it clears it. Both Soft and Weak reference has a constructor which takes in a ReferenceQueue. This queue will have the reference when it is collected by the GC. For a PhantomReference, it is mandatory that we pass a ReferenceQueue object in the constructor. That is because the phantom reference's only purpose is to know when its referent is getting cleared. So without a reference queue, the PhantomReference has no purpose as such.

A sample code is given below:

ReferenceQueue refQ = new ReferenceQueue();
//SoftReference sr = new SoftReference(new String("Soft"),refQ);
//WeakReference wr = new WeakReference(new String("Weak"),refQ);
//PhantomReference pr = new PhantomReference(new String("Phantom"), refQ);
Reference r = null;
while((r = refQ.poll())==null)
{
System.out.println ("Polling reference queue");
System.gc();
}
System.out.println (r.get());
//r.clear(); //enable only for phantom reference.


Uncomment one reference object at a time and run through the code to get an understanding. You can use eclipse debug to know what the reference object holds and when the objects are put into the queue when this code is run.

You can refer javaworld for more details.

Saturday, May 29, 2010

Adapter Pattern

    The Adapter pattern is a Structural pattern which allows us to provide a single interface between unrelated classes. There are two ways to do this: By extending the unrelated class or by using an object of the class within our class. The latter is called object composition. The former one is called as class adapter and the latter one is called as Object adapter.
    Lets see both these cases in the following example. Lets assume we have written a two Logger classes that log strings in a file and outputs on screen. 
ILogger.java
public interface ILogger
{
    public void log(String str);
}

FileLogger.java
public class FileLogger implements ILogger
{
    public void log(String str)
    {
        //write strings in file
    }
}
ConsoleLogger.java
public class ConsoleLogger implements ILogger
{
    public void log(String str)
    {
        //output strings to console
    }
}
Let us create our main class which makes use of the loggers. 
LoggerMain.java
public class LoggerMain
{
    public static void main(String[] str)
    {
        ILogger logger = null;
        if(type == FILE)
            logger = new FileLogger();
       else if(type == CONSOLE)
            logger = new ConsoleLogger();
        logger.log("Log string");
    }
}
    So far so good. Now suddenly, we get a requirement to log into the database. Fortunately, we have a third party class that does this efficiently. We really want to make use of it. The class is DBRecorder with a method recordString(String str). Obviously this class does not implement our interface. What can we do to include this class in our application? We can simply instantiate this class in our main method. But the reusability will get a hit and a small change will require a lot of coding effort and errors.
    So we create a adapter class which will solve the problem for us. The class is given below: 
DBLogger.java
public class DBLogger extends DBRecorder implements ILogger
{
    public void log(String str)
    {
        super.recordString(str);
    }
}
Now we can use this class in our main method with a simple addition like:
       if(type == DB)
           logger = DBLogger();
Simple. Isn't it? This is the whole point of adapter. The above class is an example of a class adapter.
What if your DBLogger need to extend from another class? We do not have multiple inheritance support in java. Object adapter comes to the rescue. We modify the class as follows to get the job done. 
DBLogger.java
public class DBLogger extends SomeClass implements ILogger
{
    public void log(String str)
    {
        DBRecorder recorder = new DBRecorder();
        recorder.recordString(str);
    }
}
The power of adapters are seen clearly in the above examples. In java, these adapters are simple to implement. To summarize, the main idea of Adapter is to 'make two unrelated classes work together'.

Wednesday, May 26, 2010

The Builder Pattern

    The Builder pattern, as its name suggests, builds objects step by step. Usually the building process is an abstraction to the user and the actual building is taken care of by the individual objects. The builder class is called as the 'Director'. The Director is responsible for the correct creation of the concrete object. It is better understood if we take an example. Let us assume this: We have a application which pops up a calendar. The user may want to look at only a month or look at all the months of a year. (May be this is a mind blowing application which shows appointment details in detail if a monthly calendar is shown or just blocked days of a year if yearly calendar is shown. It doesn't matter for our discussion here anyways).
    Lets see how this is done. First we need to create a abstract class which serves as a parent for the monthly and yearly calendar classes.

AbstractCalendar.java:

public abstract class AbstractUICalendar
{  
    public abstract void createTopPanel();
    public abstract void createBottomPanel();
    public abstract void buildCalendar();  
    public abstract JComponent getCalendar();     
}

Now we create the Monthly and yearly calendars.

MonthlyCalendar.java

public class MonthlyCalendar extends AbstractUICalendar
{
    @Override
    public void buildCalendar()
    {
       //put all panels at proper positions
    }
         
    @Override
    public void createBottomPanel()
    {
        //create bottom panel
    }
   
    @Override
    public void createTopPanel()
    {
       //create top panel
    }
    @Override
    public abstract JComponent getCalendar()
    {
         //return the object
    }
}

YearlyCalendar.java

public class YearlyCalendar extends AbstractUICalendar
{
    @Override
    public void buildCalendar()
    {
       //put all panels at proper positions
    }
         
    @Override
    public void createBottomPanel()
    {
        //create bottom panel
    }
   
    @Override
    public void createTopPanel()
    {
       //create top panel
    }
    @Override
    public abstract JComponent getCalendar()
    {
         //return the object
    }
}

    I have skipped all the low level details of the panel creations and calendar creation logic in the code so that you can concentrate on the Pattern instead of the how the calendar is being created.
    Now we have created the concrete classes. It time for us to create the Director. If you remember, the Director is responsible for building the required object. Below is that Director.

public class CalendarBuilder
{
    AbstractUICalendar m_calendar;
    public CalendarBuilder(AbstractUICalendar calendar)
    {
        m_calendar = calendar;
    }
    public JComponent getUI()
    {
        m_calendar.createTopPanel();
        m_calendar.createBottomPanel();
        m_calendar.buildCalendar();
        return m_calendar.getCalendar(); 

        /*The above returns the complete calendar*/
    }
}


    The Builders are ready now. Now we can make use of the builder to get a calendar of our choice. This 'choice' of the calendar UI is determined by the calendar object that we pass to the constructor of CalendarBuilder. Lets see how this is done below:

BuilderMain.java


public class BuilderMain
{
    public static void main(String[] args)

    {

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    AbstractUICalendar calendar = null;
   
    String calType = "MONTHLY"; //Hardcoded choice
   
    if(calType.equals("MONTHLY")
    {
        calendar = new MonthlyCalendar();
    }
    else
    {
        calendar = new YearlyCalendar();
    }  
    CalendarBuilder cb = new CalendarBuilder(calendar);  
    frame.getContentPane().add(cb.getUI());  
    frame.pack();
    frame.setVisible(true);
    }
}



    In the above example I have hardcoded the choice. But in real time applications, the choice may come from a button or any other parameter.
    The result of the above code is given below just for your reference. 

Monthly Calendar 

Yearly Calendar

    If you feel the Builder pattern somewhat similar to Abstract Factory pattern, read on. Or else....well.. read on anyway. The Abstract Factory pattern creates objects based on some condition and return the objects to the caller. But the builder pattern 'builds' objects step by step based on the object presented to it.
    This makes the builder pattern very flexible and you can add more classes easily.
You have more control over the build process because of the step-by-step building process of this pattern.

Tuesday, May 25, 2010

The Singleton Pattern

Perhaps the most simplest pattern of all is the ubiquitous Singleton pattern. This pattern is used in an application where no more than one instance of the class is allowed/desired. For example, a database connection can be only one for a application; No more than a single printer object can exist for an application; A application wide object.

How do we make a class return no more than one instance? One way is to make the constructor private. This makes sure no object of this class can be created outside of the class. We then add a static method which creates the object of the class, if it does not exist already, and return it to the caller.

Following code outlines our process:

public class DBConnection
{

private static DBConnection dbConnection;


private DBConnection()

{
/* Create connection here using the various DB parameters*/
}
public static DBConnection getInstance()
{
if(dbConnection == null)
{
dbConnection = new DBConnection();
}
return dbConnection;
}
/*Add other required methods*/
}

Abstract Factory Pattern


The next simpler pattern is the Abstract Factory Pattern. This pattern gives one level of abstraction above the Factory pattern. In the Factory pattern we saw the factory class returns a concrete object. In Abstract Factory Pattern, the abstract factory class returns factories which in turn returns concrete objects for use. The following image might give you the real idea behind this cool pattern.


Click on the image to enlarge it for a clear view

If you see the above picture, the Investment is the abstract factory. It gives us any of the three factories Stocks/Bonds/Mutual Funds based on some condition. Those factories in turn gives us concrete objects. (The objects from Bonds are left out in the picture because there is no space to draw them, and moreover I couldn't remember any good Bond names apart from James Bond)
The following code gives you a simple implementation of the above representation.

InvestmentFactory.java - The Abstract factory class.

public class InvestmentFactory
{
public Investment getInvestment(String risk)
{
if(risk.equals("HIGH"))
{
return new StockFundFactory();
}
else if(risk.equals("LOW"))
{
return new MutualFundFactory();
}
else
{
return new BondFactory();
}
}
}

StockFactory.java - A factory class returned by the abstract factory.

public class StockFactory extends Investment
{
public IUnit getUnit(String type)
{
IUnit stock = null;
if(type.equals("LARGE"))
{
stock = new LargeCompanyStock();
}
else if(type.equals("SMALL"))
{
stock = new SmallCompanyStock();
}
else
{
stock = new MidCompanyStock();
}
return stock;
}
}

MutualFundFactory.java - Another factory class.

public class MutualFundFactory extends Investment
{
public IUnit getUnit(String type)
{
IUnit fund= null;
if(type.equals("LARGE"))
{
fund = new LargeCapFund();
}
else if(type.equals("SMALL"))
{
fund = new SmallCapFund();
}
else
{
fund = MidCapFund();
}
return bond;
}
}

In the caller method we can use the following code snippet to get the desired object we need:

InvestmentFactory af = new InvestmentFactory();
Investment inv = af.getInvestment("HIGH");
IUnit unit = inv.getUnit("LARGE");

System.out.println(unit.totalAmount());

In these examples, the parameter which determines the object returned are Strings. I have used this for simplicity. At first this may seem confusing as it is more like the user is determining the exact object returned. But if we imagine the deciding parameter like an object returned from statements like class.forName(...) of System.getProperty(..,..), things might become clear.

A more suitable example can be given using the Java swing UI. There is a method UIManager.getSystemLookAndFeelClassName() which will return the name of the class which specifies the underlying platform's UI class(It may be the UI class for Windows, Mac or Linux). This name can act as the parameter which decides the UI object returned by the abstract factory class. The UI object thus returned itself is a factory(objects of type com.sun.java.swing.plaf.windows.WindowsLookAndFeel or com.sun.java.swing.plaf.gtk.GTKLookAndFeel etc..) from which we can get concrete objects like buttons, check boxes, lists etc.. Hope you understand this example if the previous Investment example is not clear enough.

Monday, May 24, 2010

Factory Pattern

Okay, Now we dive directly into the what and how of the design patterns.

The first design pattern we are about to see is the Factory Method pattern. It is a very simple pattern and widely used. In this pattern we use a factory class which produces objects and delivers them to us. The objects created share a common ancestor. The factory class does nothing but create objects based on a condition passed to it as a parameter.


You might have already used this kind of object creation already in some of your programs without knowing it is a factory pattern. In fact, many programmers use design patterns without knowing their official existence. Following is a Java example for the above representation. I am going to use only java and I presume that the reader has a pretty good grasp of the basics of core Java.

ILogger.java. This is the interface which will be the parent of other concrete logger classes.

public interface ILogger
{
public void log(String str);
}

ConsoleLogger.java. This class will put our log strings onto the screen.

public class ConsoleLogger implements ILogger
{
public void log(String str)
{
System.out.println(str);
}
}


FileLogger.java. This class will store the strings into a file. Where and how the file are stored are out of scope for our discussion here because we concentrate only on the pattern.

public class FileLogger implements ILogger
{
private File logFile;
public FileLogger(File logFile)
{
this.logFile = logFile;
}
public void log(String str)
{
/*
* Logic Append the string
* into the log file.
*/
}
}

LoggerFactory.java. This is the factory class which will create the objects for us. Please note that the objects created depends upon the string loggerType that we pass to the method getLogger. The string is just an example. The condition object can be of any Java object, but we rarely come across such a situation.

public class LoggerFactory
{
public static ILogger getLogger(String loggerType)
{
if(loggerType.equals("console"))
{
return new ConsoleLogger();
}
else if(loggerType.equals("file"))
{
File logFile = new File("Log file path");
return new FileLogger(logFile);
}
else
{
// return console logger by default
return new ConsoleLogger();
}
}
}

LoggerMain.java. This file does not appear in the image above, but this may be any class which uses the objects returned by the factory. Please note that errors and exceptions that may occur are not handled in these examples so that it simplifies the code for us to easily understand.

public class LoggerMain
{
public static void main(String[] args)
{
ILogger logger = LoggerFactory.getLogger(args[0]);

/*
* Use the logger to log stuff
*/
}
}

Usage:

The Factory pattern is used in situations where ,
  • The class cannot anticipate which object it needs to create until someone tells it to.
  • We need to centralize the details of which class is created.

Types of Programming Design Patterns

There are many design patterns that are categorized based on the creation of objects, composition of objects and communication between objects. When we hear the keyword 'types' we tend to think one type can be a replacement for the other(or atleast i think so :-) ). However this is not true. Every type is unique in its own way and suited best for different situations. Okay, Now the design patterns are broadly classified into three types:

  • Creational Patterns

  • Structural Patterns

  • Behavioural Patterns

  • The Creational Patterns deal with how the objects are created. These patterns show us different ways of creating objects so that the program does not depend on the way these objects are created. It helps us to delegate the creation task to a class saving us from the hard coded way of creating the objects using the "new" keyword. There are many different Creational patterns. Some of the popular patterns are:

    The Factory Pattern in which we have a simple decision making class which creates objects for us depending on some conditional parameter we pass to that class' method.

    The Abstract Factory Pattern which is one level above the factory pattern. The abstract factory returns objects which are themselves pure factory objects which in turn gives us the required objects.

    The Builder Pattern which creates complex objects step by step.

    The Prototype Pattern which creates duplicate objects by cloning.

    The popular Singleton Pattern which creates one(and only one) object of a class.

    The Structural Patterns represents how classes and objects are combined to form larger structures. Here the class patterns use inheritance to accomplish the their task and Object patterns include other objects within them to accomplish the task. Let see som of the structural patterns:

    The Adapter pattern which can be used to link two classes using an Interface.

    The Facade Pattern in which a single class can represent an underlying subsytem.

    The Proxy Pattern where a class takes the responsibility of a complex class. This can be better understood if one s familiar with the RMI in Java.

    The Decorator pattern which can add functionalities to objects dynamically.

    The Behavioural Patterns represent the different ways of communication between classes. Some of the behavioral patterns are:

    The Chain of Responsibility Pattern in which the command/message is passed through objects until the message is recognized and acted upon.

    The Command Pattern in which a command or action gets executed when an event occurs on an object.

    The Observer Pattern in which a number of concerned classes are notified of a change in a class.

    The State Pattern in which the states that the command passes through are remembered for future action.

    The Iterator pattern which provides a way to traverse a list of data in a class.

    We will see each of these patterns in detail in the further posts. I am going to use Java as a means of providing examples to better understand these patterns. Ofcourse, the reader can use any language as the examples are extremely simple and provided with rudimentary class diagrams.

    Sunday, May 23, 2010

    Design Patterns in programming

    Welcome! I believe you are one of those guys on the lookout for a simple article about design patterns. If you are a master in design patterns already, you might get bored by this 'Yet another novice article' :)

    I was one of the numerous programmers who started coding applications with curiosity right after learning a programming language. There are no words to express the joy one experiences when his code, a work of art, produces the expected results seamlessly. All goes well until someone else(or the developer himself) tries to extend the functionality of the existing program to provide new functionalities. The difficulty arises due to poor readability, poor reuse, strong coupling and finally the developer ends up modifying the code over and over again, sometimes resulting in a time that is not far less than developing the code from the scratch. Ofcourse, I was no exception. So I have decided to write down my understanding of the design patterns so that it gives a basic understanding to someone who starts a journey into the world of design patterns.

    Over the years, programmers have faced these woes and refined their programming practices such that the design minimizes coding problems that arise due to less readability, less interoperability and strong coupling between classes (and much more unspeakable horrors....). These practices are captured and documented, which we call today as the design patterns. The design patterns are more apt for Object Oriented Programming languages. The design patterns are discovered on the go. In fact many programmers who have no knowledge of design patterns, are in fact, using them! For example, inheritence itself is a design pattern.

    I am going to write simple articles about design patterns which might serve as a starting point to learning design patterns. There are numerous sites out there which teach all the possible design patterns that exist, in detail which you can refer if you need to go to an advanced level(as if you don't know this!!).