Sunday, 26 June 2011

Inheritance versus composition in Java

are two important concepts you should swear by. Both help us to relate classes and achieve code resuse. But which one do we use?
Comparing inheritance and composition.
  1. In inheritance, a change to the method interface/definition of the superclass ripples down to the sublasses (if the method is overriden) and also to the clients of the sublasses thus making the superclass very fragile. In case of composition the change is limited to the containing class and not the clients.
  2. With inheritance, you cannot change the overriden method in the subclass without changing the superclass; reason it wont compile. With composition, you can change the interface of the method in the containing class that uses the method/behaviour of the contained class without touching it.
  3. In case of inheritance the classes are bound statically at compile time or as soon as the subclass is defined and will remain with the subclass till its lifetime. where as in case of composition, the behaviour can be changed at runtime.
  4. Though, with inheritance you can add new subclasses without affecting the code. Where as this is not the case with composition, unless you use composition with interface.
Going by the definition of inheritance, one should use it only if there is a IS-A relationship between classes and should not be merely used to get code re-use or polymorphism.
If you want to reuse code and there is no IS-A relationship , use composition and if you need polymorphism, but there is no IS-A relationship, use composition with interfaces.

I will add examples to explain each comparison points, in my next iteration of this post.

Friday, 24 June 2011

Class Loaders - simplified - part 2

In my last post I said I will be discussing about NoClassDefFoundError and the ClassNotFoundException

You can load the classes in two ways one is static loading and second way is to dynamically loading the class.
  1. Static loading - load a class statically using the new operator.
  2. Dynamic loading - programmatically loading the class using the class loader functions at run time.Using Ex Class.forName/ClassLoader.findSystemClass/ClassLoader.loadClass
You can get NoClassDefFoundError for the following reason
1) You have not set the class path, so the class loader cannot find the .class file ( TestClass)
2) You have set the class path, but the class path does not contain the .class file/jar does not contain the specified .class (the call to the new operator fails)
3) It could also happen if the class fails to load as the static initializer block fails for some reason.

You can get ClassNotFoundException if
1) You have set the class path, but the class path does not contain the .class file/jar does not contain the specified .class , so the dynamic loading call class.forName fails.

Use the below example of a class that tries to refer to another TestClass

public class ClassLoaderExceptionTest
public static void main(String args[]) throws Exception
Class class = Class.forName("TestClass"); //dynamically loading the class
//Throws ClassNotFoundException if TestClass is missing or removed after compilation/ not present in //class path
TestClass testClass = new TestClass(); // static loading
//Throws NoClassDefFoundError if TestClass is missing or removed after compilation/ not present in class //path
class TestClass{

Thursday, 23 June 2011

Class Loaders - simplified - part 1

As discussed in my previous post, class loaders is one of the components of JVM. It is responsible for finding and loading the class at run time.

Classes are loaded into the JVM as they are referenced by name in a class that is already running in JVM. The first class is loaded into memory by invoking the static void main method of the class. All subsequent classes are loaded by classes which are previously loaded and running.

The following class loaders are created by the JVM
  1. Bootstrap or primordial class loader: Is the default class loader which is associated with the JVM. You can hook your own custom class loader instead of the default. All the JDK internal classes java.* packages i.e the ones that belong to rt.jar or i18n.jar are loaded by this class loader. (as defined in the sun.boot.class.path system property)
  2. Extension class loader: loads classes that are part of the extensions directory typically the lib/ext directory of the JRE are loaded by this class loader. (as defined in the java.ext.dirs system property)
  3. System class loader: loads classes that are part of the system class path (as defined by the java.class.path system property which is set by the CLASSPATH environment property, or -classpath / -cp command line options)
Classes loaded by different class loaders are placed into separate name spaces inside the Java virtual machine.
Class Loaders not just loads but performs the following activities in sequence.
  1. Loading - finding and importing the binary data of the type in the .class file.
  2. Linking - involves verification, preparation and resolution.
    • Verification - involves ensurinNumbered Listg that the binary data is structurally valid, else will throw VerifyError.
    • Preparation - involves allocating memory for class variables and initializing the memory to the default values.
    • Resolution - is the process of transforming the symbolic references from the type into direct references.
  3. Initialization - invokes code that initializes class variables to their proper starting values.
Class loaders use delegation model to load classes. Whenever a class requires to be loaded, the class loaders will contact its parents to load the class before they themselves try. Once the class loaders loads the class, the child class loader in the hierarchy will never reload the class. Classes loaded by the child class loaders have visibility into the classes loaded by parent class loaders but the reverse is not true. If there are sibling class loaders, then the sibling class loaders do not see the classes loaded by each other.

More on class loaders in my next blog. I will cover scenarios when you would encounter NoClassDefFoundError and ClassNotFoundException.

Wednesday, 22 June 2011


Java Virtual machine -is an abstract computing machine. It is the component of java technology that gives it hardware and OS independence. It has its own instruction set and manipulates various memory areas at run time.

The architecture as defined in the specification makes it possible to have different JVM implementation for different hardware platforms.The architecture of the JVM as defined in the specification is shown in the diagram below

It consists of
  1. Class Loader subsystem
  2. Run time data areas
  3. Execution engine
  4. Native method interface
  5. Native method libraries.
Class loader subsystem - is responsible for loading types (classes and interfaces). The .class files adhere to fix format and it contains JVM instructions or byte codes, a symbol table and other ancillary information.
Execution engine - is responsible for the actual execution of the instructions contained in the method of the loaded classes.
Run time data areas - the JVM organizes the memory it needs to execute a programs into various data areas. These various data areas may be shared by all the threads in the program or some data areas may be thread specific
  • The method area and heap is shared by all the threads
  • where as the PC registers,java stack, native method stack are thread specific.
Each instance of JVM has one memory area and one heap.
  • Method area: holds the details of each class loaded by the class loader subsystem.
  • Heap: holds every object being created by the threads during execution, including the main thread.

As each thread executes in the JVM, it gets its own PC register and the java stack. They are not shared among threads.

  • PC registers: For any executing thread the register holds the address of the next instruction to execute.
  • Java Stack: the stack stores the state of the method invocation (state - includes the local variables, the method parameters, the return value if any and intermediate or temporary calculations) of the thread (in stack frames - current execution method stack frame is the topmost)
  • Native method stack : the state of the native method are stored in native method stacks in an implementation dependent way, so also possibly the registers or an other implementation dependent memory areas.

More on class loader subsystem in my next blog.

You can find useful references

Java Platform

is a platform for java development. It is a software only platform which is ported on hardware platforms It comprises of two major components
  1. JVM - Java virtual machine - it is the component which add portability aspect to Java. JVM understand byte codes (compiled .class files from .java classes). Byte codes are the machine language of the JVM. JVM then interprets byte codes to the actual underlying machine language. Compilation happens only once and interpretation happens each time the program is executed.
  2. Java API - a set of classes written using java and which runs on the JVM. It consists of lot of useful classes which help us in development of applications etc.
You can find useful references

Sunday, 5 June 2011

Concurrent call exception using Seam and JSF

I got this exception, while working on a Ajax+JSF+Seam project. I ignored it for a while till it came back haunting at the UAT.
A little investigation into the exception and googling help me find the answer. Here is what happened, I had a ajax component which was taking a long time to render the response, in the meanwhile another request was sent to the server through some other component action ex a submit button, this call failed to render the response, reason being the first call had obtained a lock in the render_reponse and hadnt released it, so the second call failed to obtain a lock and hit back with the exception.
You could solve this in one of the following ways,
1. Showing a wait dialog so that the users understand that there is some processing going on.
2. queueing the request, a4j has a component named 'queue' which you can leverage.

If there are better ways to handle this, I will be glad to add it to my kitty.