Friday, June 15, 2012

Exploring Java 7 : Try-with-resources

Try-with-Resource is new featured added in Java 7. Personally, I like this feature very much, as it helps to reduce a lot of boiler plate code.

Consider a scenario, where we have to release a system resource, like JDBC Connection or File Stream. Prior to Java 7, it meant that developer has to write a lot of boiler plate code to release that resource. In order to ensure releasing of resource in all the situations, one has to use finally block as well for exception cases. Consider following example, written with Java 6:

String readFirstLine(String path) throws IOException {
  BufferedReader br = new BufferedReader(new FileReader(path));
  try {
   return br.readLine();
  } finally {
   if (br != null)
Clearly, one has to write almost 4-5 lines for closing each resource. Now, what Java 7 did is that it made the process of closing resource automatic.

In Java 7, a resource is defined as "An object of type java.lang.AutoCloseable.". This AutoCloseable interface has a single method close() and this method is invoked automatically when a resource is used with try block. See below example:
String readFirst(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
   return br.readLine();

Impressive!!! Isn't it? We have reduced boiler plate code drastically and there is no scope of accidentally forgetting to close a resource. All resource will be freed automatically.

Few points to remember:
  • A resource must be declared in parenthesis, immediately after try block.
  • A Try-with-Resource can have catch and finally blocks, just as with try block.
  • There can be multiple resources in a single Try-with-Resource block
  • public void readEmployees(Connection con){
      String sql = "Select * from Employee";
      try (Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(sql)){
       //Work with Statement and ResultSet   
      } catch (SQLException sqe) {
  • In case of multiple resources, close() method of all the resources is called, and order of calling close() method is reverse of declaration

Friday, June 1, 2012

Interface or Abstract Class

What is the difference between an Abstract Class and an Interface?
Well, isn't it an interesting question or for few, a foolish question?

For a number of Java newbies, the only difference between two is, "You can't have method body in Interface.". Well, I would say that it is technically (Implementation vise) correct, but doesn't reflect the concept.

Abstract Class
An abstract class, is the most generalized form of an Entity hierarchy (In Java, a Class is an entity), such that it doesn't represent a real entity on its own, but provides a basis on which real entities can be build within that hierarchy. An abstract class provides a default behavior and also provide abstract behavior (Operations that must be override by the real classes).

An interface, on the other hand is a contract that states that you have to agree to provide following operations if you agree to abide by me, i.e. an entity that agrees to abide by the contract of interface, will have to provide the behavior (operations) declared in interface.

Interface or Abstract Class
Next question is when to use abstract class and when use an Interface? Though it many a depends on requirements as well, but I follow a thumb rule,
  • If I have to build a class hierarchy, I should consider generalization. Many a time I will reach to most crude form of generalization, i.e. at an abstract level. I would declare abstract methods and will also define common behavior for few of the methods. This would be my abstract class.
  • On the other hand, if I want to expose a particular behavior to the client, then I would define an interface. 

Further, I would suggest that one should go through different Java APIs, and spend some time understanding when and why they used interface or abstract class. Java APIs are excellent source for learning on building design blocks for any OOPs language.

Wednesday, December 14, 2011

Singleton Pattern: Am I implementing it Correctly? - Part II

In my last post, I discussed implementation of Singleton Pattern in a Single Threaded Environment. There was a very good discussion on whether about very existence of this pattern as well. Actually it is an ever going debate, few people think that it is an anti pattern and few think it is a simple solution of a common problem.

My intent of this post (and previous also) is to discuss on how to implement it, rather than whether to use it!!! So, let's start discussing Singleton Pattern in a Multi-threaded environment.

Singleton Pattern in Multi-Thread environment:

We have seen using static factory to implement Singleton Pattern in a single thread environment and also discussed problems associated with it. When in Multi-threaded environment, there are other problems as well.

What will happen if two threads simultaneously try to access static factory method (getInstance() method)? It will result in two instance of class, though we required only one instance. Clearly, singleton pattern is broken.

This problem is not only associated with Java, but also to other languages as well, like C++.  A naive solution is to synchronize the static factory method, so that at any given time, only one thread can execute getInstance() method. So, even if we ignore the problems arising from reflection (see previous post) and want to use singleton pattern, then it would be used in this way:
public class SingletonInMultiThread {
 private static SingletonInMultiThread singletonInstance; 
 private SingletonInMultiThread(){} 
 public SingletonInMultiThread getInstance(){
  if(singletonInstance == null) singletonInstance = new SingletonInMultiThread();
  return singletonInstance;

Well, there is no problem (other than we discussed for reflection) in above code, but there is an overhead of synchronization every time, as we need synchronization only at the time of creation.There are two ways to resolve this problem.

One is to instantiate the variable at the time of declaration and remove synchronization from static factory method.To resolve this synchronization
public class SingletonInMultiThread {
 private static SingletonInMultiThread singletonInstance = new SingletonInMultiThread(); 
 private SingletonInMultiThread(){} 
 public SingletonInMultiThread getInstance(){  
  return singletonInstance;
Another solution is to use infamous Double Checked Locking (Just google it and can find thousands of articles saying same thing), but it is also broken, see DCL.

But, Good News is that with Java 5 and using volatile for instance variable, you can seal this DCL broking :)

So, we have seen how we can use Singleton Pattern in a multi-thread environment, but with above discussion, there are still few issues:
  • We ignore the breaking of Singleton Pattern by reflection
  • It is quite cumbersome to implement Singleton Pattern in multi-threaded environment

As I said in previous post, starting from Java 5, a much easier way to control number of instances is to use ENUM. With all the advantages we discussed earlier, it is threadsafe!!!

Whenever you need to control number of instances of a type, it is better to consider Enum. Enums are special classes whose number of instances are controlled by JVM itself!!!