Archive

Archive for May, 2012

Decorator Pattern in Java

Decorator Pattern

 

Motivation

Extending an object‘s functionality can be done statically (at compile time) by using inheritance however it might be necessary to extend an object’s functionality dynamically (at runtime) as an object is used.

Consider the typical example of a graphical window. To extend the functionality of the graphical window for example by adding a frame to the window, would require extending the window class to create a FramedWindow class. To create a framed window it is necessary to create an object of the FramedWindow class. However it would be impossible to start with a plain window and to extend its functionality at runtime to become a framed window.

 

Intent

  • The intent of this pattern is to add additional responsibilities dynamically to an object.

 

Implementation

The figure below shows a UML class diagram for the Decorator Pattern:
Decorator Pattern Implementation - UML Class Diagram The participants classes in the decorator pattern are:

  • Component – Interface for objects that can have responsibilities added to them dynamically.
  • ConcreteComponent – Defines an object to which additional responsibilities can be added.
  • Decorator – Maintains a reference to a Component object and defines an interface that conforms to Component’s interface.
  • Concrete Decorators – Concrete Decorators extend the functionality of the component by adding state or adding behavior.

Description

The decorator pattern applies when there is a need to dynamically add as well as remove responsibilities to a class, and when subclassing would be impossible due to the large number of subclasses that could result.

 

Applicability & Examples

Example – Extending capabilities of a Graphical Window at runtime

Decorator Pattern Example - UML Class Diagram

In Graphical User Interface toolkits windows behaviors can be added dynamically by using the decorator design pattern.

Consequences

  • Decoration is more convenient for adding functionalities to objects instead of entire classes at runtime. With decoration it is also possible to remove the added functionalities dynamically.
  • Decoration adds functionality to objects at runtime which would make debugging system functionality harder.
Advertisements

Making your class compatible with Java hash maps: overriding hashCode() and equals()

If  you have prior knowledge of hashing, then you may have an idea of how to write the hash function itself. On this page we’ll discuss the nuts and bolts you need to actually plug your hash function into a Java class and therefore use instances of that class as a hash map key. (Note that we concentrate on HashMaps here, but the points we discuss generally hold for related classes such as ConcurrentHashMap and HashSet.)

The basics: override hashCode() and equals()

Put very simply, there are two methods that a class needs to override to make objects of that class work as hash map keys:

public int hashCode();
public boolean equals(Object o);

As you might expect, the hashCode() method is where we put our hash function. Note that HashMap will not do any extra caching of the hash code. So if calculating the hash is relatively expensive (as in the case of String) it may be worth explicitly caching the hash code.

The equals() method

The equals() method must return true if the fields of the current object equal those of the object passed in, else return false. By “equal”, we generally mean that primitive fields match via the == operator, and objects are either both null or both non-null and match via the equals() method. Note two important constraints on equals():

  • if x.equals(y) returns true, then the hash codes of x and y must be identical;
  • it must be reflexive and transitive: that is, x.equals(y) must return the same value as y.equals(x), and if x.equals(y) and y.equals(z), then x.equals(z) must also be true (see below for what this actually means in real terms!).

The first of these is generally common sense given that the purpose of a hash function is to “narrow down a search” which will ultimately be performed using the equals() to perform the final check for a match. The second is more or less common sense, but it does mean, for example, that we can’t allow a null reference to equal an “empty” object. It also means, strictly speaking, that a subclass cannot add new variable comparisons to the equals() method2.

Example

Now let’s see an example. We’ll look at a simple class that encapsulates a pair of screen coordinates. We assume that individually, the X and Y coordinates are essentially random, but that the maximum coordinate in each case will be in the order of a couple of thousand (in other words will have about 10 or 11 bits of randomness). So to make the hash code, we pick a number that is roughly halfway between these bits, then find a prime (or at worst odd) number that is close to 211. Our old favourite of 31 (=25-1) will do us fine. The equals() method is trivial, but note the convention of returning false if the object passed in isn’t of a compatible type.

public class CoordinatePair {
  private int x, y;
  public int hashCode() {
 return (x * 31) ^ y;
  }
  public boolean equals(Object o) {
    if (o instanceof CoordinatePair) {
      CoordinatePair other = (CoordinatePair) o;
      return (x == other.x && y == other.y);
    }
    return false;
  }
}

1. I think this convention predates Java 5 generics: arguably, we really don’t expect a case where equals() will be called against an object of an incompatible type and should just apply the case an rely on the resulting runtime exception if the cast fails.
2. The problem with subclassing can be explained with a quick example. Suppose we extend Rectangle (whose equals() method effectively compares its co-ordinates and dimensions, although via the Rectangle2D base class) to make a class called ColouredRectangle, whose equals() method returns true if and only if the colours of the rectangles are identical. Now we have the problem that a plain Rectangle, if passed a ColouredRectangle to its equals() method, would return true provided the co-ordinates and dimensions were the same, discounting the colour; whereas the other way round, ColouredRectangle.equals() would always return false (because it wasn’t comparing against another ColouredRectangle).

The Java Class Loader – Base Concept

Class loading is one of the most powerful mechanisms provided by the Java Language Specification. All Java programmers should know how the class loading mechanism works and what can be done to suit their needs. By understanding the class loading mechanism you can save time that would otherwise be spent on debugging ClassNotFoundException , ClassCastException , etc.

Class Loaders

In a Java Virtual Machine (JVM), each and every class is loaded by some instance of a java.lang.ClassLoader. The ClassLoader class is located in the java.lang package and you can extend it to add your own functionality to class loading.

When a new JVM is started by java HelloWorld, the bootstrap class loader is responsible for loading key java classes like java.lang.Object and other runtime code into memory. The runtime classes are packaged inside jre/lib/rt.jar file. We cannot find the details of the bootstrap class loader in the java language specification, since this is a native implementation. For this reason the behavior of the bootstrap class loader will differ across JVM’s.

Maze Behind Class Loaders

All class loaders are of the type java.lang.ClassLoader. Other than the bootstrap class loader all class loaders have a parent class loader. These two statements are different and are important for the correct working of any class loaders written by a developer. The most important aspect is to correctly set the parent class loader. The parent class loader for any class loader is the class loader instance that loaded that class loader.

We have two ways to set the parent class loader:

public class CustomClassLoader extends ClassLoader{

public CustomClassLoader(){
super(CustomClassLoader.class.getClassLoader());
}
}

Or

public class CustomClassLoader extends ClassLoader{

public CustomClassLoader(){
super(getClass().getClassLoader());
}
}

The first constructor is the preferred one, because calling the method getClass() from within a constructor should be discouraged, since the object initialization will be complete only at the exit of the constructor code. Thus if the parent class loader is correctly set, whenever a class is requested out of a ClassLoader instance using loadClass(String name) method, if it cannot find the class, it should ask the parent first. If the parent cannot find the class, the findClass(String name) method is invoked. The default implementation of findClass(String name) will throw ClassNotFoundException and developers are expected to implement this method when they subclass java.lang.ClassLoader to make custom class loaders.

Inside the findClass(String name) method, the class loader needs to fetch the byte codes from some arbitrary source. The source may be a file system, a network URL, another application that can spit out byte codes on the fly, or any similar source that is capable of generating byte code compliant with the Java byte code specification. Once the byte code is retrieved, the method should call the defineClass() method, and the runtime is very particular about which instance of the ClassLoader is calling the method. Thus if two ClassLoader instances define byte codes from the same or different sources, the defined classes are different.

For example, lets say I’ve a main class called MyProgram. MyProgram is loaded by the application class loader, and it created instances of two class loaders CustomClassLoader1 and CustomClassLoader2 which are capable of finding the byte codes of another class Student from some source. This means the class definition of the Student class is not in the application class path or extension class path. In such a scenario the MyProgram class asks the custom class loaders to load the Student class, Student will be loaded and Student.class will be defined independently by both CustomClassLoader1 and CustomClassLoader2. This has some serious implications in java. In case some static initialization code is put in the Student class, and if we want this code to be executed one and only once in a JVM, the code will be executed twice in the JVM with our setup, once each when the class is separately loaded by both CustomClassLoaders. If we have two instances of Student class loaded by these CustomClassLoaders say student1 and student2, then student1 and student2 are not type-compatible. In other words,

Student student3 = (Student) student2;

will throw ClassCastException, because the JVM sees these two as separate, distinct class types, since they are defined by different ClassLoader instances.

The Need For Your Own Class loader

For those who wish to control the JVM’s class loading behavior, the developers need to write their own class loader. Let us say that we are running an application and we are making use of a class called Student. Assuming that the Student class is updated with a better version on the fly, i.e. when the application is running, and we need to make a call to the updated class. If you are wondering that the bootstrap class loader that has loaded the application will do this for you, then you are wrong. Java’s class loading behavior is such that, once it has loaded the classes, it will not reload the new class. How to overcome this issue has been the question on every developers mind. The answer is simple. Write your own class loader and then use your class loader to load the classes. When a class has been modified on the run time, then you need to create a new instance of your class loader to load the class. Remember, that once you have created a new instance of your class loader, then you should make sure that you no longer make reference to the old class loader, because when two instances of the same object is loaded by different class loaders then they are treated as incompatible types.

Writing Your Own Class loader

The solution to control class loading is to implement custom class loaders. Any custom class loader should have java.lang.ClassLoader as its direct or distant super class. Moreover you need to set the parent class loader in the constructor. Then you have to override the findClass() method. Here is an implementation of a custom class loader.

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
public class CustomClassLoader extends ClassLoader {
    public CustomClassLoader(){
        super(CustomClassLoader.class.getClassLoader());
    }

    public Class loadClass(String className) throws ClassNotFoundException {
         return findClass(className);
    }

    public Class findClass(String className){
        byte classByte[];
        Class result=null;
        result = (Class)classes.get(className);
        if(result != null){
            return result;
        }

        try{
            return findSystemClass(className);
        }catch(Exception e){
        }
        try{
           String classPath =    ((String)ClassLoader.getSystemResource(className.replace('.',File.separatorChar)+".class").getFile()).substring(1);
           classByte = loadClassData(classPath);
            result = defineClass(className,classByte,0,classByte.length,null);
            classes.put(className,result);
            return result;
        }catch(Exception e){
            return null;
        } 
    }

    private byte[] loadClassData(String className) throws IOException{

        File f ;
        f = new File(className);
        int size = (int)f.length();
        byte buff[] = new byte[size];
        FileInputStream fis = new FileInputStream(f);
        DataInputStream dis = new DataInputStream(fis);
        dis.readFully(buff);
        dis.close();
        return buff;
    }

    private Hashtable classes = new Hashtable();
}</i>

Here is how to use the CustomClassLoader. 

<i>public class CustomClassLoaderTest {

     public static void main(String [] args) throws Exception{
        CustomClassLoader test = new CustomClassLoader();
        test.loadClass(com.test.HelloWorld);
     }
}

Summary

Many J2EE application servers have a  hot deployment  capability, where we can reload an application with a new version of class definition, without bringing the server VM down. Such application servers make use of custom class loaders. Even if we don’t use an application server, we can create and use custom class loaders to fine-control class loading mechanisms in our Java applications. So have fun with custom loaders

%d bloggers like this: