Thursday, April 5, 2012

Java Singleton design pattern tutorial


Java Singleton design pattern is one of the design pattern that governs the instantiation of an object in Java. This design pattern suggest that only one instance of a Singleton object is created by the JVM. This pattern is useful when exactly one object is needed to coordinate actions across the system. Also it can be generalized to restrict the objects to certain number of instances like say 5 objects only.
Related: Free Design Pattern Reference Card

Class diagram of Singleton class

Following is the class diagram of a singleton class. The constructor is kept private to avoid normal instantiation of objects and all the instantiations are done only through getInstance() method.

How the Singleton pattern works?

Following is the source of simple class that follows singleton pattern.
01
02
03
04
05
06
07
08
09
10
11
12
13
public class SimpleSingleton {
    private static SimpleSingleton INSTANCE = new SimpleSingleton();
 
    //Marking default constructor private
    //to avoid direct instantiation.
    private SimpleSingleton() {
    }
 
    //Get instance for class SimpleSingleton
    public static SimpleSingleton getInstance() {
        return INSTANCE;
    }
}
In above code snippet, we have declared a static object reference to SimpleSingleton class called INSTANCE and is returned every time getInstance() is called. In this design, the object will be instantiate when the class will be loaded and before the method getInstance() is being called. Demand loading (lazy loading) also called initialization on demand holder idiom is not seen in this implementation.
We can change this code to add lazy init (Instantiate only when first time getInstance() is called) into this. Following is the code snippet for that.
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
public class SimpleSingleton {
    private SimpleSingleton singleInstance = null;
 
    //Marking default constructor private
    //to avoid direct instantiation.
    private SimpleSingleton() {
    }
 
    //Get instance for class SimpleSingleton
    public static SimpleSingleton getInstance() {
 
        if(null == singleInstance) {
            singleInstance = new SimpleSingleton();
        }
 
        return singleInstance;
    }
}

Do you need Singleton pattern?

Singletons are useful only when you need one instance of a class and it is undesirable to have more than one instance of a class.
When designing a system, you usually want to control how an object is used and prevent users (including yourself) from making copies of it or creating new instances. For example, you can use it to create a connection pool. It’s not wise to create a new connection every time a program needs to write something to a database; instead, a connection or a set of connections that are already a pool can be instantiated using the Singleton pattern.
The Singleton pattern is often used in conjunction with the factory method pattern to create a systemwide resource whose specific type is not known to the code that uses it. An example of using these two patterns together is the Abstract Windowing Toolkit (AWT). In GUI applications, you often need only one instance of a graphical element per application instance, like the Print dialog box or the OK button.

Problems with Singletons

A simple design pattern like Singleton also has few problem:

Construct in a multi-thread environment

It may happen that in a multi-threaded environment two or more threads enter the method getInstance() at the same time when Singleton instance is not created, resulting into simultaneous creation of two objects.
Such problems can be avoided by defining getInstance() method synchronized.
1
public static synchronized SimpleSingleton getInstance() { }

Cloning can spoil the game

Although we have taken enough precaution to make the Singleton object work as singleton, Cloning the object can still copy it and result into duplicate object. The clone of the singleton object can be constructed using clone() method of the object. Hence it is advisable to overload clone() method of Object class and throw CloneNotSupportedException exception.

1
2
3
4
5
public Object clone() throws CloneNotSupportedException {
 
      throw new CloneNotSupportedException();
 
}
The Singleton pattern is widely used and has proved its usability in designing software. Although the pattern is not specific to Java, it has become a classic in Java programming.

Wednesday, April 4, 2012

Difference between ServletRequest.getRequestDispatcher and ServletContext.getRequestDispatcher


  • request.getRequestDispatcher(“url”) means the dispatch is relative to the current HTTP request.
    Example code: RequestDispatcher reqDispObj = request.getRequestDispatcher("/home.jsp"); 
  •  
  • getServletContext().getRequestDispatcher(“url”) means the dispatch is relative to the root of the ServletContext.
    Example code:RequestDispatcher reqDispObj = getServletContext().getRequestDispatcher("/ContextRoot/home.jsp");

Difference between ServletConfig and ServletContext

  • Signature: public interface ServletConfig
    ServletConfig is implemented by the servlet container to initialize a single servlet using init(). That is, you can pass initialization parameters to the servlet using the web.xml deployment descriptor. For understanding, this is similar to a constructor in a java class.
Example code:
<servlet>
<servlet-name>ServletConfigTest</servlet-name>
<servlet-class>com.javapapers.ServletConfigTest</servlet-class>
<init-param>
<param-name>topic</param-name>
<param-value>Difference between ServletConfig and ServletContext</param-value>
</init-param>
</servlet>

  • Signature: public interface ServletContext
    ServletContext is implemented by the servlet container for all servlet to communicate with its servlet container, for example, to get the MIME type of a file, to get dispatch requests, or to write to a log file. That is to get detail about its execution environment. It is applicable only within a single Java Virtual Machine. If a web applicationa is distributed between multiple JVM this will not work. For understanding, this is like a application global variable mechanism for a single web application deployed in only one JVM.
The ServletContext object is contained within the ServletConfig object. That is, the ServletContext can be accessed using the ServletConfig object within a servlet. You can specify param-value pairs for ServletContext object in <context-param> tags in web.xml file.
Example code:
<context-param>
<param-name>globalVariable</param-name>
<param-value>javapapers.com</param-value>
</context-param>

Difference between JSP include directive and JSP include action

<%@ include file=”filename” %> is the JSP include directive.
  • At JSP page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally JSP include directive is used to include header banners and footers. The JSP compilation procedure is that, the source JSP page gets compiled only if that page has changed. If there is a change in the included JSP file, the source JSP file will not be compiled and therefore the modification will not get reflected in the output.
  • <jsp:include page=”relativeURL” /> is the JSP include action element.
    The jsp:include action element is like a function call. At runtime, the included file will be ‘executed’ and the result content will be included with the soure JSP page. When the included JSP page is called, both the request and response objects are passed as parameters. If there is a need to pass additional parameters, then jsp:param element can be used. If the resource is static, its content is inserted into the calling JSP file, since there is no processing needed.

    there is a limit of 64kb size in JVM for method. So the include directive can run into trouble as its all one method. Whereas the action is considered a separate process.

Tuesday, April 3, 2012

can overloaded methods be overridden too ?

Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future.

What's the difference between display: none and visibility: hidden?

The display: none and visibility: hidden CSS properties appear to be the same thing, but they aren't.
Answer: These two style properties do two different things.
visibility: hidden hides the element, but it still takes up space in the layout.
display: none removes the element completely from the document. It does not take up any space, even though the HTML for it is still in the source code.

what does load-on-startup do in web.xml ?

  1. <servlet>  
  2.         <servlet-name>action</servlet-name>  
  3.         <servlet-class>  
  4.             org.apache.struts.action.ActionServlet  
  5.         </servlet-class>  
  6.         <init-param>  
  7.             <param-name>config</param-name>  
  8.             <param-value>/WEB-INF/struts-config.xml</param-value>  
  9.         </init-param>  
  10.         <load-on-startup>1</load-on-startup>  
  11.     </servlet>  
 Servlets are not loaded until they are first accessed by a request. This may result in a slow access time for the first user. The load-on-startup tag allows you to force the container to load and initialize the servlet at startup. 

The load-on-startup element indicates that this servlet should be loaded (instantiated and have its init() called) on the startup of the web application. The optional contents of these element must be an integer indicating the order in which the servlet should be loaded. If the value is a negative integer, or the element is not present, the container is free to load the servlet whenever it chooses. If the value is a positive 128 integer or 0, the container must load and initialize the servlet as the application is deployed. The container must guarantee that servlets marked with lower integers are loaded before servlets marked with higher integers. The container may choose the order of loading of servlets with the same load-on-start-up value.