Wednesday, July 13, 2011

How to Read File in Java

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* This program reads a file line by line and print to the console.
*
*/
public class FileRead {
public static void main(String[] args) {
File file = new File("C:\\MyFile.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;

try {
fis = new FileInputStream(file);

//BufferedInputStream is added for fast reading.
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);

// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {

// Reads the line from the file and print it to the console.
System.out.println(dis.readLine());
}

// close all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Monday, June 27, 2011

Singleton Pattern


Singleton design pattern is the first design pattern I learned (many years back). In early days when someone asks me, “do you know any design pattern?” I quickly and promptly answer “I know singleton design pattern” and the question follows, “do you know anything other than singleton” and I stand stumped!

A java beginner will know about singleton design pattern. At least he will think that he knows singleton pattern. The definition is even easier than Newton’s third law. Then what is special about the singleton pattern. Is it so simple and straightforward, does it even deserve an article? Do you believe that you know 100% about singleton design pattern? If you believe so and you are a beginner read through the end, there are surprises for you.
There are only two points in the definition of a singleton design pattern,
  1. there should be only one instance allowed for a class and
  2. we should allow global point of access to that single instance.
GOF says, “Ensure a class has only one instance, and provide a global point of access to it. [GoF, p127]“.
The key is not the problem and definition. In singleton pattern, trickier part is implementation and management of that single instance. Two points looks very simple, is it so difficult to implement it. Yes it is very difficult to ensure “single instance” rule, given the flexibility of the APIs and many flexible ways available to access an instance. Implementation is very specific to the language you are using. So the security of the single instance is specific to the language used.

Strategy for Singleton instance creation

We suppress the constructor and don’t allow even a single instance for the class. But we declare an attribute for that same class inside and create instance for that and return it.Factory design pattern can be used to create the singleton instance.
package com.javapapers.sample.designpattern;
public class Singleton {
  private static Singleton singleInstance;
    private Singleton() {}
  public static Singleton getSingleInstance() {
    if (singleInstance == null) {
      synchronized (Singleton.class) {
        if (singleInstance == null) {
          singleInstance = new Singleton();
        }
      }
    }
    return singleInstance;
  }
You need to be careful with multiple threads. If you don’t synchronize the method which is going to return the instance then, there is a possibility of allowing multiple instances in a multi-threaded scenario. Do the synchronization at block level considering the performance issues. In the above example for singleton pattern, you can see that it is threadsafe.

Early and lazy instantiation in singleton pattern

The above example code is a sample for lazy instantiation for singleton design pattern. The single instance will be created at the time of first call of the getSingleInstance() method. We can also implement the same singleton design pattern in a simpler way but that would instantiate the single instance early at the time of loading the class. Following example code describes how you can instantiate early. It also takes care of the multithreading scenario.
package com.javapapers.sample.designpattern;
public class Singleton {
  private static Singleton singleInstance = new Singleton();
  private Singleton() {}
  public static Singleton getSingleInstance() {
    return singleInstance;
  }
}

Singleton and Serialization

Using serialization, single instance contract of the singleton pattern can be violated. You can serialize and de-serialize and get a new instance of the same singleton class. Using java api, you can implement the below method and override the instance read from the stream. So that you can always ensure that you have single instance.
ANY-ACCESS-MODIFIER Object readResolve() throwsObjectStreamException;

Usage of Singleton Patter in Java API

java.lang.Runtime#getRuntime() java.awt.Desktop#getDesktop()