Singleton Design Pattern

Singleton Design pattern is all about making sure that only object can be created per class loader hierarchy.

There are some situations where we want only one object in  our application such as cache object, Hibernate SessionFactory object which contains configuration.In these Conditions creating multiple objects in applications are wast of memmory.


Here is example of How we can make sure that only one object can remain  in application to avoid memmory wast.

.Date Util

public class DateUtil {
private DateUtil() {
// no-op
System.out.println("constructor...");
}
}

This is simple class .Anyone can create n number of Objects from above class using new Operator.
We want to restrict our application can contain only one object of DateUtil class.


Step 1.

The basic Step of creating object everyone knows DateUtil dt=new DateUtil();nwe must stop user to creating object using new operator.

answer in make constructor private and let the user get object through factory method.

public class DateUtil extends AppClass implements Cloneable {
private static DateUtil instance;

private DateUtil() {
// no-op
System.out.println("constructor...");
}


public static DateUtil getInstance() {
if (instance == null) {
instance = new DateUtil();
}
}
return instance;
}

}

Here we restricted user to create n number of objects using factory method.Everytime when user need object he will call DateUtil.getInstance() method to get object.

It Seems that this is perfect example but still there are some ares where we need to workout.

This programm can provide single object in non multi threaded environment but in mutithreaded environment problm may arise..
Lets Assume tha 2 Threads are trying to create object at same time they check condition]
      if (instance == null) {

         they will found object is nout created thy may create new object.

Difference between ConcurrentHashMap, Hashtable and Synchronized Map in Java

Though all three collection classes are thread-safe and can be used in multi-threaded, concurrent Java application, there is significant difference between them, which arise from the fact that how they achieve their thread-safety. Hashtable is a legacy class from JDK 1.1 itself, which uses synchronized methods to achieve thread-safety. All methods of Hashtable are synchronized which makes them quite slow due to contention if number of thread increases. Synchronized Map is also not very different than Hashtable and provides similar performance in concurrent Java programs. Only difference between Hashtable and Synchronized Map is that later is not a legacy and you can wrap any Map to create it's synchronized version by using Collections.synchronizedMap() method. On the other hand, ConcurrentHashMap is especially designed for concurrent use i.e. more than one thread. By default it simultaneously allows 16 threads to read and write from Map without any external synchronization. It is also very scalable because of stripped locking technique used in internal implementation of ConcurrentHashMap class. Unlike Hashtable and Synchronized Map, it never locks wholeMap, instead it divides the map in segments and locking is done on those. Though it perform better if number of reader threads is greater than number of writer threads. 

Collections classes are heart of Java API we can  improved performance of Java application by using ArrayList where legacy codes were unnecessarily using Vector etc. Prior Java 5, One of the major drawback of Java Collection framework was lack of scalability. In multi-threaded Java application synchronized collection classes like Hashtable and Vector quickly becomes bottleneck; to address scalability JDK 1.5 introduces some good concurrent collections which is highly efficient for high volume, low latency system electronic trading systems In general those are backbone for Concurrent fast access of stored data. In this tutorial we will look on ConcurrentHashMap, Hashtable,HashMap and synchronized Map and see difference between ConcurrentHashMap and Hashtable and synchronized Map in Java. 

Example of Validations Using Java Script AND Pagination Using Display Tags0

This applications shows how to do validations against a registration page
and while revering data how to display in pages.

This Example Contains 2 Modules
          1.Register User(Used validations Also).
          2.Get all Users and Display them using Pagination.

This Example Contains Some Design Patterns.
      1.Service(BusinesDelegate).
      2.BO(BusinesObject).
      3.DAO

Here is  Project Structure.




Note:if u don't know how to create maven directory structure find blog post. 




Step 1.
   Create a new html file name it index.html. Now take the required fields with 2 Buttons
     1.Register and Second is GetAllRecords.

index .html

<!DOCTYPE html>
<body onload="document.registration.userid.focus();">
</form>9

<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Form Validation using a sample registration form</title>
<meta name="keywords" content="example, JavaScript Form Validation, Sample registration form" />
<meta name="description" content="This document is an example of JavaScript Form Validation using a sample registration form. " />
<link rel='stylesheet' href="css/index.css" type='text/css' />
<script src="java_script_code/index.js"></script>
</head>

<h1>Registration Form</h1>
<p>Use tab keys to move from one input field to the next.</p>
<form action="register" method="post" name='registration' onSubmit="return formValidation();">
<ul>
<li><label for="userid">User id:</label></li> <li><input type="text" name="userid" size="12" /></li>
<li><label for="passid">Password:</label></li> <li><input type="password" name="passid" size="12" /></li>
<li><label for="username">Name:</label></li> <li><input type="text" name="username" size="50" /></li>
<li><label for="address">Address:</label></li> <li><input type="text" name="address" size="50" /></li>
<li><label for="country">Country:</label></li> <li><select name="country">
<option selected=" " value="Default">(Please select a country)</option>
<option value="Australia">Australia</option>
<option value="Canada">Canada</option>
<option value="India">India</option>
<option value="Russia">Russia</option>
<option value="USA">USA</option>
     </select></li>
<li><label for="zip">ZIP Code:</label></li> <li><input type="text" name="zip" /></li>
<li><label for="email">Email:</label></li> <li><input type="text" name="email" size="50" /></li>
<li><label id="gender">Sex:</label></li>
    <li><input type="radio" name="sex" value="Male" /><span>Male</span></li>
<li><input type="radio" name="sex" value="Female" /><span>Female</span></li>
<li><label>Language:</label></li> 
<li><input type="checkbox" name="language" value="english" checked /><span>English</span></li>
<li><input type="checkbox" name="language" value="noenglish" /><span>Non English</span></li>
<li><label for="desc">About:</label></li>
<li><textarea name="desc"  id="desc"></textarea></li>
<li><input type="submit" name="submit" value="Submit" /></li>
</ul>
</form>
<form action="getDetails" method="get">
Click here to get All Records <input type="submit" name="b1"
value="GetDetails" />

</body>

</html>

 2. Java Script Code

function formValidation() {
var uid = document.registration.userid;
var passid = document.registration.passid;
var uname = document.registration.username;
var uadd = document.registration.address;
var ucountry = document.registration.country;
var uzip = document.registration.zip;
var uemail = document.registration.email;
var umsex = document.registration.msex;
var ufsex = document.registration.fsex;
if (userid_validation(uid, 5, 12)) {
if (passid_validation(passid, 7, 12)) {
if (allLetter(uname)) {
if (alphanumeric(uadd)) {
if (countryselect(ucountry)) {
if (allnumeric(uzip)) {
if (ValidateEmail(uemail)) {
if (validsex(umsex, ufsex)) {
}
}
}
}
}
}
}
}
return false;

}
function userid_validation(uid, mx, my) {
var uid_len = uid.value.length;
if (uid_len == 0 || uid_len >= my || uid_len < mx) {
alert("User Id should not be empty / length be between " + mx + " to "
+ my);
uid.focus();
return false;
}
return true;
}
function passid_validation(passid, mx, my) {
var passid_len = passid.value.length;
if (passid_len == 0 || passid_len >= my || passid_len < mx) {
alert("Password should not be empty / length be between " + mx + " to "
+ my);
passid.focus();
return false;
}
return true;
}
function allLetter(uname) {
var letters = /^[A-Za-z]+$/;
if (uname.value.match(letters)) {
return true;
} else {
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
function alphanumeric(uadd) {
var letters = /^[0-9a-zA-Z]+$/;
if (uadd.value.match(letters)) {
return true;
} else {
alert('User address must have alphanumeric characters only');
uadd.focus();
return false;
}
}
function countryselect(ucountry) {
if (ucountry.value == "Default") {
alert('Select your country from the list');
ucountry.focus();
return false;
} else {
return true;
}
}
function allnumeric(uzip) {
var numbers = /^[0-9]+$/;
if (uzip.value.match(numbers)) {
return true;
} else {
alert('ZIP code must have numeric characters only');
uzip.focus();
return false;
}
}
function ValidateEmail(uemail) {
var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (uemail.value.match(mailformat)) {
return true;
} else {
alert("You have entered an invalid email address!");
uemail.focus();
return false;
}
}
function validsex(umsex, ufsex) {
x = 0;

if (umsex.checked) {
x++;
}
if (ufsex.checked) {
x++;
}
if (x == 0) {
alert('Select Male/Female');
umsex.focus();
return false;
} else {
alert('Form Succesfully Submitted');
window.location.reload();
return true;
}
}

Step 2.web.xml

 This is the configuration file where all registerServlet and getDeatilsServlet are configured.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>SimpleWebApp</display-name>
  <servlet>
    <servlet-name>RegisterationServlet</servlet-name>
    <servlet-class>com.registeration.RegisterationServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RegisterationServlet</servlet-name>
    <url-pattern>/register</url-pattern>
  </servlet-mapping>
  <servlet>
    <servlet-name>GetRecordsServlet</servlet-name>
    <servlet-class>com.registeration.GetAllRecords</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>GetRecordsServlet</servlet-name>
    <url-pattern>/getDetails</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
</web-app>



3.RegisterationServlet.java

 This is RegisterationServlet who gets the input elements from the index.jsp.This Servlet create object of Service class.This class is acting as BusinessDelegate Design Pattern.who just get the request from servlet and acts as middleman to do any work.Thats why it is called Service or BusinessDelegate Design Pattern.
In This class We are Creating the object of BO class which is nothing but simple class which contains all the fields which are in the registration page. The Reason of using this class instead of direct passing string values to service class is that is bad Practice passing 5 and more arguments to any method.
BO stands for BusinessObject which carry the values which are reqiured as per our business Logic.


package com.registeration;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.util.BO;
import com.util.Service;

public class RegisterationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}

protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
int id=Integer.parseInt(request.getParameter("userid"));
String password=request.getParameter("passid");;
String name=request.getParameter("username");;
String address=request.getParameter("address");;
String country=request.getParameter("country");;
int zipCode=Integer.parseInt(request.getParameter("zip"));
String email=request.getParameter("email");;
String sex=request.getParameter("sex");;
String language=request.getParameter("language");;
String desc=request.getParameter("desc");
    BO bo=new BO();
       bo.setId(id);
       bo.setPassword(password);
       bo.setName(name);
       bo.setAddress(address);
       bo.setCountry(country);
       bo.setZipCode(zipCode);
       bo.setEmail(email);
       bo.setSex(sex);
       bo.setLanguage(language);
       bo.setDesc(desc);
       
     Service service=new Service();  
             int rs=service.register(bo);
             String msg="";
           if(rs==1){
             msg="Sucess";
           }
           else{
            msg="Failed";
           }
           
           request.setAttribute("msg", msg);
           RequestDispatcher rd=request.getRequestDispatcher("Result.jsp");
               rd.forward(request, response);
}

}

Step3 :Create a new class name it Service.java.

 This class creates the object of DAO class Object nothing but DesignPattern which is used for separating the Persistence code(Operations on Database Code) from the BusinessLogic class(Service class).

package com.util;

import java.sql.SQLException;
import java.util.List;

import com.dao.DAO;


public class Service {
public int register(BO bo) {
DAO dao=new DAO();
int result=0;
   try {
result=dao.register(bo);
} catch (SQLException e) {
System.out.println("Failed to Register");
e.printStackTrace();
}
return result;
}
public List<BO> getAllRecords(){
 DAO dao=new DAO();
 List<BO> list=null;
        try {
 list=dao.getAllRecords();
} catch (SQLException e) {
System.out.println("Failed to getRecords");
e.printStackTrace();
}
             return list;
}
}


Step4 :Create a new class name it DAO.java.

This class is responsible for interacting to Database.for Getting connection we are using ConnectionFactory Class given below.The benefit of using ConnectionFactory class seperate so we are not require to write the code of getting connection in every class.


package com.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.util.BO;
import com.util.ConnectionFactory;

public class DAO {
private final String INSERT="INSERT INTO TEMP2 VALUES(?,?,?,?,?,?,?,?,?,?)";
private final String GET_ALL_RECORDS="SELECT * FROM TEMP2";
public int register(BO bo) throws SQLException {
Connection con=null;
PreparedStatement pst=null;
con= ConnectionFactory.getConnection();
pst=con.prepareStatement(INSERT);
System.out.println(bo);
   pst.setInt(1,bo.getId());
   pst.setString(2, bo.getPassword());
   pst.setString(3, bo.getName());
   pst.setString(4, bo.getAddress());
   pst.setString(5, bo.getCountry());
   pst.setInt(6, bo.getZipCode());
   pst.setString(7, bo.getEmail());
   pst.setString(8, bo.getSex());
   pst.setString(9, bo.getLanguage());
   pst.setString(10, bo.getDesc());
  
return pst.executeUpdate();
}
public List<BO> getAllRecords() throws SQLException{
Connection con=null;
PreparedStatement pst=null;
ResultSet rs=null;
BO bo=null;
     List<BO> list=null;
     list=new ArrayList<BO>();
con= ConnectionFactory.getConnection();
pst=con.prepareStatement(GET_ALL_RECORDS);
 rs=pst.executeQuery();
  while(rs.next()){
  bo=new BO();
  bo.setId(rs.getInt("USERID"));
  bo.setPassword(rs.getString("PASSWORD"));
  bo.setName(rs.getString("NAME"));
  bo.setAddress(rs.getString("ADDRESS"));
  bo.setCountry(rs.getString("COUNTRY"));
      bo.setZipCode(rs.getInt("ZIPCODE"));
      bo.setEmail(rs.getString("EMAIL"));
      bo.setSex(rs.getString("SEX"));
      bo.setLanguage(rs.getString("LANGUAGE"));
      bo.setDesc(rs.getString("DESCRIPTION"));
      list.add(bo);
    
  }
  return list;
}
}


Step5 :Create a new class ConnectionFactory.java.

 This class contains the common logic(Boiler Plate Logic) instaed of writing this code in every DAO we are writing separate
.
package com.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionFactory {
   public static  Connection getConnection(){
 Connection con=null;
  
   try{
   Class.forName("oracle.jdbc.driver.OracleDriver");
   }catch(ClassNotFoundException e){
   e.printStackTrace();
   }

   
      try {
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger");
} catch (SQLException e) {
e.printStackTrace();
}
       return con;  
   }
}


Step 6 :Create a new jsp name it Display.jsp

   This jsp file will contains the code for displaying the data which has been stored in database in       pagination Manner.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
 <%@ taglib uri="http://displaytag.sf.net" prefix="display" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<display:table name="sessionScope.records" pagesize="5"    uid="id">
                <display:column property="id" title="id" />
                <display:column property="password" title="password" />
                <display:column property="name" title="name" />
                <display:column property="address" title="address" />
                <display:column property="country" title="country" />
                <display:column property="zipCode" title="zipCode" />
                <display:column property="email" title="email" />
                <display:column property="sex" title="sex" />
                <display:column property="language" title="language"  />
                <display:column property="desc" title="desc" />
            </display:table>

</body>
</html>