Wednesday, June 29, 2011

Java 5 Enums

Enums or enumerated types basically means a type that can be defined to have a certain set of fixed values as per the problem domain. Historically, enums (via enum keyword and any associated semantics) were missing from the featureset provided by versions upto Java 1.4.
However developers tried to achieve the "same enum effect" via something like this:
Example 1:
public class Currency {
  public static final int USD = 1;
  public static final int EUR = 2;
  public static final int GBP = 3;
  public static final int YEN = 4;
}

public class CurrencyConverter {
  public void convertCurrency(int fromCurrency, int toCurrency) { ... }

  public static void main(String[] args) {
    CurrencyConverter cc = new CurrencyConverter();
    cc.convertCurrency(Currency.USD, Currency.YEN);
  }
}
Additional currencies could be added to the Currency class by defining new constants. However, the convertCurrency (int, int) method lacks typesafety since the method signature indicates it can accept any int. However, the only acceptabe range of ints is 1 through 4. If we call the method outside of the range of agreed upon constants , e.g. convertCurrency(8, 10), the program fails.

The above can be avoided if we accept that Enumerations should be treated as a separate type. Implementing them as a sequence of integers is not helpful. To define enumerations as their own type, you do the following:

1. Replace the primitive ints above with 'static final' object references to the same class defining the enumerated constants.
2. Disallow any object creation of the class via a private constructor.

Example 2:
public final class Currency {
  public static final Currency USD = new Currency(1);
  public static final Currency EUR = new Currency(2);
  public static final Currency GBP = new Currency(3);
  public static final Currency YEN = new Currency(4);

  int value;

  private Currency(int value){
    this.value = value;
  }
}

public class CurrencyConverter {
   public void convertCurrency(Currency fromCurrency, Currency toCurrency) { ... }

   public static void main(String[] args) {
     CurrencyConverter cc = new CurrencyConverter();
     cc.convertCurrency(Currency.USD, Currency.YEN);
   }
}
The convertCurrency(Currency, Currency) now takes the Currency type instead of an int.

Secondly the acceptable values of Currency can only be defined inside the class due to the private constructor.This along with the fact that Currency is a final class ensures that Currency.USD, Currency.EUR, Currency.GBP and Currency.YEN are the only instances of the Currency class.

It also means that we can use the identity comparison (==) operator instead of the equals() method when comparing enum values. Identity comparison (==) is always faster than equals since we are only comparing object references in the former as opposed to object values in the latter.

However the above typesafety approach comes with the following disadvantages:
1. The above implementation is not Serializable and Comparable by default. It means we can have issues using them in the context of RMI and EJBs. In case, if we make them Serializable, constructing the object again creates a new instance of the same Currency by ignoring its private constructor completely and does not retrieve the same instance that was serialized. This means == comparison fails to identify the equality of a serialized and a non-serialized Currency. Also it means we no longer have a unique single instance of the currency type. We have to implement more boiler-plate code like implementing the readResolve method as suggested in http://www.javaworld.com/javaworld/javatips/jw-javatip122.html?page=2.

2. We cannot switch over the above enum values (remember it is easier to switch over ints) to get any business logic done. If we need to switch, it can be facilitated by providing a getValue() method that returns the int value.

Example 3:
Inside Currency class,
public class Currency {
      ....

      public int getValue() {
        return value;
      }
   }

   public class CurrencyConverter {
     public void convertCurrency(Currency fromCurrency, Currency toCurrency) { ... }
   }
Java 5 enums are a typesafe feature and overcome all the above problems listed with the Enumerated pattern. In addition to facilitating a way to list a set of constant values, they also provide features such as :

1. All defined enums implicitly extend from java.lang.Enum just as all objects implicitly extend from java.lang.Object.

2. The above feature taks care of default implementation for toString(), equals(), hashCode() methods.

3. They are Serializable and Comparable by default without generating duplicate instances during deserialization

4. They can be used in switch-case statements.

5. They can have behavior ( via member variables , methods , constructors, interface implementations etc) in addition to just specifying the constants.

Simplest example of Java 5 enum class with no additional behavior.

Example 4:

public enum Currency { USD,GBP,EUR,YEN }

public class CurrencyConverter
{
   public void printCurrencies() {
     for (Currency currency : Currency.values()) {
        System.out.println(currency);
        System.out.println(currency.ordinal());
   }
} 

}
Currency is an enum type, and all the above enum values, viz USD, GBP, EUR, YEN are of type Currency.

We can iterate through all the instances of Currency via the static values() method and take advantage of the toString() method in the print statement.

Example 5:
We can also add behavior via member fields and methods.

public enum Currency 
  {
    USD("United States"),
    GBP("United Kingdom"),
    EUR("Europe"),
    YEN("Japan")

    String country;

   public Currency(String country){
     this.country = country;
   }

   public Currency getCurrencyForCountry(String country) {
     return Currency.valueOf(country);
   }
 }

When you need to provide custom behavior based on the enum values, there are 2 ways of doing it. Either you switch case based on the enum values in the application code or a yet better way is to move the custom logic inside the enum class as follows:

Example 6:
public class Client 
   {
     enum HttpStatusCode
     {
        HTTP200("HTTP 200") {
         @Override
         void printMessage() {
            System.out.println("Successful Transaction ");
         }
     },
     HTTP401("HTTP 401 Error") {
        @Override
        void printMessage() {
          System.out.println("Authentication Failure");
        }
     },
     HTTP404("HTTP 404 Error") {
          @Override
          void printMessage() {
             System.out.println("Requested resource not found at specified location");
           }
     },
     HTTP500("HTTP 500 Error") {
       @Override
       void printMessage() {
          System.out.println("An error occured on server-side, please have   patience.");
      }
    };

    String statusString;

    HttpStatusCode(String statusString) {
       this.statusString = statusString;
    }

    abstract void printMessage();
 }

   public static void main(String[] args)
   {
     HttpStatusCode status = connectToServer();
     status.printMessage();
   }
 }

Switching over case statements could be used if you have no option of modifying the enum class code. This can happen in cases where the enum class is generated - e.g. using JAXB - from an XSD. More on this in a later blog.

So this covers the basics of Java 5 Enums. Java 5 also provides 2 data structures - java.util.EnumSet and java.util.EnumMap. More on this again will be in yet another blog.


Monday, January 5, 2009

Tomcat 6 and class loading

In continuation with the previous blog entry, I would also like to write about Tomcat 6 (in particular) and class loading pattern that it adopts. Java allows the creation of custom class loaders by implementing the java.lang.ClassLoader. Now Tomcat 6 creates the following class loaders on startup. They share a parent-child relationship too, but NOTE that the delegation pattern is a bit different as will be explained

Although invisible in default installation of Tomcat 6, there are additional shared and server class loaders also available and they fall below the Common class loader in the hierarchy. Each of the class loaders has a responsibility to load classes from certain specific areas, noted below:  

1. Bootstrap + Extension class loader - It loads the Java run-time classes in the JDK as well as any classes from the jars in the Extensions folder.  

2. System class loader - As noted in the previous blog, the System class loader is responsible for loading the classes and the Jar classes present in the CLASSPATH. But an important NOTE here: Tomcat clears the user-set CLASSPATH entry in its startup.bat or startup.sh file. Instead it sets the CLASSPATH to be following: $CATALINA_HOME/bin/bootstrap.jar $CATALINA_HOME/bin/tomcat-juli.jar  

3. Common class loader - This is a Tomcat 6 provided class loader. It loads the classes present in the following folder - $CATALINA_HOME/lib. These classes are available to Tomcat as well as all the web applications that will be hosted on this instance of Tomcat. Although developers can reference the APIs from the jars inside the $CATALINA_HOME/lib directory, they shouldn't be placing their own custom classes and/or jars in there. If developers need certain custom classes and/or jars to be shared by all web applications, then they should be placed where the shared class loader can see them. Note that Tomcat 6.0.14 the $CATALINA_HOME/shared/lib directory does not exist. So this can be done in Tomcat 6 as foll:
  • Create your own $CATALINA_HOME/shared/lib directory.
  • Modify $CATALINA_HOME/conf/catalina.properties by changing the line: shared.loader = ${catalina.home}/shared/lib
However the above does not apply to certain 3rd party libraries such as database drivers etc where Tomcat itself would need to set up data sources. Such jars have to be placed in the $CATALINA_HOME/lib folder for the common class loader to see. One can also add more jars for the common class loader without placing them under the $CATALINA_HOME/lib folder. This can be done by modifying $CATALINA_HOME/conf/catalina.properties by changing the property common.loader as above.  

4. WebappX class loaders - Tomcat creates a class loader for every webapp that is deployed in its instance. This class loader loads classes under WEB-INF/classes and WEB-INF/lib folder. It is for these class loaders where the delegation model deviates, thanks to the Servlet Specification which states as follows: "It is recommended also that the [web] application class loader be implemented so that classes and resources packaged within the WAR are loaded in preference to classes and resources residing in container-wide library JARs."
However the above specification cannot override the Java standard delegation model of delegating to Bootstrap and System class loaders. It only is used to override the parent-child relationships that are introduced by Tomcat - ie. Common, Shared and WebappX class loaders. So when an application requests a class, the class loading hierarchy is as follows:
  1. The bootstrap class loader looks in the core Java classes folders.
  2. The system class loader looks in the $CATALINA_HOME/bin/bootstrap.jar and
  3. $CATALINA_HOME/bin/tomcat-juli.jar
  4. The WebAppX class loader looks in WEB-INF/classes and then WEB-INF/lib
  5. The common class loader looks in $CATALINA_HOME/lib folder.
  6. The shared class loader looks in $CATALINA_HOME/shared/classes and $CATALINA_HOME/shared/lib if the shared.loader property is set in conf/catalina.properties file.

Sunday, January 4, 2009

Java and Class loading delegation model

The role of a class loader in Java is to hide the details of loading classes - like searching the file system (local as well as network) for the class file, loading the class file, returning it to JVM as a Class class so that JVM can use the Class class to instantiate the requested object in the application. Since J2SE, the JVM is provided 3 distinct primary classloaders -
  1. Bootstrap class loader - This class loader is written in native language and comes as part of the JVM implementation. It loads all the core Java classes. (e.g java.lang.* etc). The location of these jars depends on the implementation of JVM. Sun's JVM looks in the jdk/jre/lib directory. 
  2. Extension class loader - Usually, developers make use of the CLASSPATH environment variable to load application classes, 3rd party jars etc. However, the CLASSPATH can become too unwieldy to handle and prone to errors using this approach. So since Java 1.2 , we can drop the 3rd party jars into a standard extension directory - jdk/jre/lib/ext - and JVM will find them. The extension class loader loads all the classes found in one or more of these extension directories.
  3. System class loader - This class loader locates and loads the classes in the directories and jar files specified on the CLASSPATH variable. It also loads the application's main class (the one containing the main() method).

 The above 3 exist in a parent-child relationship as follows:

A delegation model is utilized by the JVM in order to determine which class loader amongst the above 3 to use to load a particular class. The model works in a "Delegate to Parent-Before-Looking" as follows: When an application requests a Class (e.g String str = "Hello World"; or MyClass myobj = new MyClass()) :
  1. Each class loader delegates the request to its parent.
  2. Once the topmost class loader is reached, the bootstrap class loader, it tries to load the class. If it is unable, its child will try.
  3. If one of the class loaders finds the class, it is returned as a Class object. Following the delgation pattern , if the lowermost class loader in the hierarchy (System class loader) does not find the class, a ClassNotFoundException is thrown.

Sunday, December 7, 2008

Java 5 Concurrency: The Executor framework

The Java platform has always provided support for multi-threaded/concurrent programming. However, prior to Java 5, the support was in the form of primitive constructs in the programming language itself. Java 5 steps up and provides concurrency utility frameworks and data structures in the java.util.concurrent package. One of the utilities provided is the task scheduling framework better known as the Executor framework. The JVM runs as a process and our application is one of the threads in the JVM. There are various other "system" threads running to do tasks like garbage collection, memory management etc. But from the application's perspective, there is the single "main" thread to begin with. The application, in itself, can spawn a number of threads to perform various helper tasks for various reasons like performance etc. Prior to Java 5 , spawning a new thread to perform a task was most commonly done as follows, although you could also do by extending the Thread class, but it is not highly recommended:

public void mainMethod() {
 HelperTask task = new HelperTask(); // Step 1: Create an object representing the task
 Thread t = new HelperThread(task);  // Step 2: Create a new thread for executing the task
 t.start();                        //  Step 3: Start the new thread
}

public class HelperTask implements Runnable {
public void run() {
      doHelperTask();
}
}
We have the following issues:
  1. Most of the code related to thread creation and task delegation to the thread is a part of the application itself. We need a way to abstract the above steps away from the application.
  2. Also what if we have multiple helper tasks or a scenario where every single user action requires a new Thread to be spawned to process? Creating a lot many threads with no bounds to the maximum threshold can cause out application to run out of memory.
  3. Secondly although threads are light-weight (but only as compared to the process) , creating them utilizes a lot of resources. In such a situation, having a ThreadPool is a better solution so that only fixed number of Threads are created and re-used later.
  4. Another short-coming of the Runnable interface's void run() method is that the task executed within run() has no way of returning any result back to the main thread. So work-arounds designed around that would be that the asynchronous task either updates certain database table(s) or some file(s) or some such external data structure(s) to communicate the result to the main thread.
The Executor framework addresses all the above issues and in addition also provides additional life-cycle management features for the threads. The Executor framework consists of the following important interfaces:

  1.  Callable: This interface is similar in concept to Runnable interface, ie it represents the asynchronous task to be executed. The only difference is that its call() method returns a value, ie the asynchronous task will be able to return a value once it is done executing. 
  2. Executor, ExecutorService and ScheduledExecutorService - Each of these interfaces adds more functionality to the previous one in thread and their life-cycle management. The Executor abstracts the Thread creation (as seen in Step 1 above) and executes all Runnable tasks. The ExecutorService extends the Executor and is able to execute Callable tasks in addition to Runnable tasks. It also contains life cycle management methods. The ScheduledExecutorService allows us to schedule the asynchronous tasks thereby adding support for delayed and periodic task execution. 
  3. Future: This interface represents the result of the asynchronous task which itself could be represented as Callable. The ExecutorService which can execute Callable tasks returns a Future object to return the result of the Callable task.

Thursday, November 13, 2008

Essentials of a Software Engineer

Sites like Digg usually have highest number of "diggs" on stuff like "Top 5/10/n" things on varied topics. Recently a co-worker sent me one such popular article about "Top 10 concepts that every software engineer should know". This was just in time as I was preparing to start this blog about the various techniques that would enable a Java engineer to be more pragmatic regardless of the kind of applications being developed and the myriad of technologies/frameworks being used . In my opinion, it is more essential to know these principles thoroughly and put them in practice before jumping to learning any new frameworks. Most of the frameworks - open source or otherwise - are usually the usage of the design principles in practice to solve commonly encountered problems. Good Object-Oriented(OO) design is the key principle here. As Rod Johnson points out here, "It's possible to design a [J2EE] application so badly that, even if it contains beautifully written Java code at an individual object level, it will still be deemed a failure. A [J2EE] application with an excellent overall design but poor implementation code will be an equally miserable failure. ... adherence to good OO principles brings real benefits. OO design is more important than any particular implementation technology (such as [J2EE], or even Java). Good programming practices and sound OO design underpin good [Java/J2EE] applications. Bad Java code is bad J2EE code."

Sunday, September 28, 2008

Overview of Web Service Stacks

There are currently the following open-source Java Web Service stacks in the market today.There could be more that I am unaware of, but at least the following contribute more significantly to the market share.
  1. Apache Axis1 and Apache Axis2
  2. Apache CXF
  3. Spring-WS
  4. Sun’s Metro available via Java EE 5 GlassFish container
  5. JbossWS
  6. XFire - which is now merged and transformed to being CXF.
This article is a comparative interview with each of the web service stack’s Principal Engineers and their vision for their product. http://www.infoq.com/articles/os-ws-stacks-background The second article is a comparison between Apache’s 3 products – Axis1, Axis2 and CXF. http://www.theserverside.com/tt/articles/article.tss?l=AxisAxis2andCXF Both of these articles are non-biased articles with no claims of one being better than the other. They leave it up to users to pick the one most matching their needs and demands. Sun has now published the standards for Web Services and it has now become imperative for all the Web Service stacks to provide implementations of those for conformance. Every web service stack provides the core functionality of:
  1. Providing an easy-to-use deployment option. 
  2. Correct Web service/operation invocation for the particular message(SOAP/REST). This further involves in the following order -
  • Receiving the message over the correct transport endpoint(Endpoint is an abstraction to represent URL and port),
  • Figure out the operation intended to perform based on the message, and then
  • Invoke the correct Java method mapping to the operation.
    3.  Pre-processing the messages via handlers to perform various functions like authentication, logging, custom processing etc.
    4. Marshaling/Unmarshaling mechanism of the request and response structures to/from Java<=>XML.
   5.  In addition, today's web service stacks are expected to provide implementations for the various WS-* standards that exist.

With respect to points # 2 and # 4 above, Mark Hansen has correctly pointed out:
The key technology for efficient SOA is efficient and accurate Java/XML mapping or more generically known as the OXM (Object-XML Mapping)as pointed out by Spring-WS. At the SOA level, system standards are specified using platform independent XML messages (SOAP/REST) and WSDL operations (which themselves are in XML). But at the language level (Java/C#/VB etc), the systems that are the real engines behind the functionality of SOA are implemented using objects and methods. The more seamless effortless and accurate OXM solution that a web service engine provides the more popular it will be.

Programming Java Web Services

For someone who is a total newbie to the world of Java Web Services(JWS), here's a list of the different JSRs/standards within the realm of JWS that are available with Java EE 5 and Java SE 6. They all have a particular purpose in the whole orchestration of JWS.
  1. JAX-WS 2.0 (Java API for Xml-Web Services) - specified by JSR 224.
  2. This was formerly JAX-RPC 1.1. JAX-RPC 1.1 was a standards-based implementation, but the binding and parsing layers underneath it were proprietary. When JAX-RPC 1.1 needed a major overhaul, the next JAX-RPC version would have been JAX-RPC 2.0 But the industry evolved more than just doing RPC-style web services. So to accommodate the message-style web services as well, which are becoming more and more common, "RPC" was dropped to become a more general JAX-WS 2.0
  3. JAXB 2.0 (Java API for Xml Binding) - specified by JSR 222.
  4. This specification defines and nominates JAXB as the default mechanism for serializing and de-serializing the XML messages contained within the SOAP message and Java objects. There are sure other ways to do this job via other Java-XML binding mechanisms - like XMLBeans, JiBX, Castor etc. But the JWS specs (defined by Sun) decided to make JAXB 2.0 as the "default" standard.
  5. WS-Metadata 2.0 (Web Services Metadata) - specified by JSR 181.
  6. Deploying Web services is quite a feat. One would normally require a set of deployment descriptors a la typical J2EE applications. But from Java EE 5 onwards, we now have web services-specific metadata annotations to achieve the deployment.
  7. WSEE 1.2 - Web Services for Java EE - specified by JSR 109.
  8. This defines the program model and run-time beahvior of Web Services in the Java EE container.
All these standards can be complex to understand at first, and after surfing a lot on the web for an in-depth perspective, I have finally landed on the book "SOA Using Java Web Services" by Mark D. Hansen.