Tuesday, July 9, 2013

How to resolve de-serialization issue in Singleton design pattern ( de-serialization always creates a new instance)

Adding readResolve():

So, till now you must have taken your decision that how you would like to implement your singleton. Now lets see other problems that may arise even in interviews also.
Lets say your application is distributed and it frequently serialize the objects in file system, only to read them later when required. Please note that, de-serialization always creates a new instance. 

Please refere more details on below link:

Wednesday, June 5, 2013

What is a Transaction (ACID)? What does setAutoCommit do?

What is a Transaction (ACID)? What does setAutoCommit do?

A 43: A transaction is a set of operations that should be completed as a unit. If one operation fails then all the other operations fail as well. For example if you transfer funds between two accounts there will be two operations in the set
1. Withdraw money from one account.
2. Deposit money into other account.
These two operations should be completed as a single unit. Otherwise your money will get lost if the withdrawal is
successful and the deposit fails. There are four characteristics (ACID properties) for a Transaction.

Atomicity :
All the individual
operations should
either complete or fail.

Consistency:
The design of the
transaction should
update the database
correctly.

Isolation :
Prevents data being corrupted by concurrent
access by two different sources. It keeps
transactions isolated or separated from each
other until they are finished.
Ensures that the database
is definitely updated once
the Transaction is
completed.

Durability:
Transactions maintain data integrity. A transaction has a beginning and an end like everything else in life. The
setAutocommit(….), commit() and rollback() are used for marking the transactions (known as transaction
demarcation). When a connection is created, it is in auto-commit mode. This means that each individual SQL
statement is treated as a transaction and will be automatically committed immediately after it is executed. The way
to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:
try{
Connection myConnection = dataSource.getConnection();
// set autoCommit to false
myConnection .setAutoCommit(false);
withdrawMoneyFromFirstAccount(.............); //operation 1
depositMoneyIntoSecondAccount(.............); //operation 2
myConnection .commit();
}
catch(Exception sqle){
try{
myConnection .rollback();
}catch( Exception e){}
}
finally{
try{if( conn != null) {conn.close();}} catch( Exception e) {}
}

The above code ensures that both operation 1 and operation 2 succeed or fail as an atomic unit and consequently
leaves the database in a consistent state. Also turning auto-commit off will provide better performance.

Monday, June 3, 2013

Reuse of database connection in jsp/servlet

Reuse of database connection in jsp/servlet:


Hope the below example will help you for reuse of database connection 

Servlet class:

package com.jspcr.servlets;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

/**
* An example of a JSP superclass that can be selected with
* the extends attribute of the page
* directive.  This servlet automatically loads the
* JDBC-ODBC driver class when initialized and establishes
* a connection to the USDA nutrient database.
*/
public abstract class NutrientDatabaseServlet
   extends HttpServlet
   implements HttpJspPage
{
   protected Connection con;

   /**
   * Initialize a servlet with the driver
   * class already loaded and the database
   * connection established.
   */
   public void init(ServletConfig config)
      throws ServletException
   {
      super.init(config);
      try {
         Class.forName("com.mysql.jdbc.Driver");
         con = DriverManager.getConnection("jdbc:mysql://localhost/usda15");
      }
      catch (Exception e) {
         throw new UnavailableException(e.getMessage());
      }

      jspInit();
   }

   /**
   * Closes the database connection when
   * the servlet is unloaded.
   */
   public void destroy()
   {
      try {
         if (con != null) {
            con.close();
            con = null;
         }
      }
      catch (Exception ignore) {}

      jspDestroy();
      super.destroy();
   }

   /**
   * Called when the JSP is loaded.
   * By default does nothing.
   */
   public void jspInit() {}

   /**
   * Called when the JSP is unloaded.
   * By default does nothing.
   */
   public void jspDestroy() {}

   /**
   * Invokes the JSP's _jspService method.
   */
   public final void service(
         HttpServletRequest request,
         HttpServletResponse response)
      throws ServletException, IOException
   {
      _jspService(request, response);
   }

   /**
   * Handles a service request.
   */
   public abstract void _jspService(
         HttpServletRequest request,
         HttpServletResponse response)
      throws ServletException, IOException;

JSP Page:

<%--
  Copyright (c) 2002 by Phil Hanna
  All rights reserved.
  
  You may study, use, modify, and distribute this
  software for any purpose provided that this
  copyright notice appears in all copies.
  
  This software is provided without warranty
  either expressed or implied.
--%>
<%@ page extends="com.jspcr.servlets.NutrientDatabaseServlet" %>
<%--
   This JSP page subclasses the NutrientDatabaseServlet
   parent class, which automatically loads the
   database driver and establishes the connection.
--%>
<%@ page import="java.io.*,java.sql.*" %>
Food Groups

Food Groups

CodeDescription
<%
   // Execute a query

   Statement stmt = con.createStatement();
   String sql = "SELECT * FROM FD_GROUP ORDER BY FDGP_DESC";
   ResultSet rs = stmt.executeQuery(sql);
   while (rs.next()) {
      String code = rs.getString(1);
      String desc = rs.getString(2);
%>
http://astore.amazon.com/httpsjavatop1-20
   <%= code %>
   <%= desc %>
<%
   }
   
   // Close the database objects

   rs.close();
   stmt.close();
%>

Tuesday, May 14, 2013

How do you make a Servlet thread safe?


A typical (or default) Servlet life cycle creates a single instance of each servlet and creates multiple threads to handle the service() method. The multithreading aids efficiency but the servlet code must be coded in a thread safe manner. The shared resources (e.g. instance variables, utility or helper objects etc) should be appropriately synchronized or should only use variables in a read-only manner. Having large chunks of code in synchronized blocks in your service methods can adversely affect performance and makes the code more complex.

Alternatively it is possible to have a single threaded model of a servlet by implementing the marker or null
interface javax.servlet.SingleThreadedModel. The container will use one of the following approaches to ensure

Thread safety:
􀂃 Instance pooling where container maintains a pool of servlets.
􀂃 Sequential processing where new requests will wait while the current request is being processed.


Best practice:

 It is best practice to use multi-threading and stay away from the single threaded model of the
servlet unless otherwise there is a compelling reason for it. Shared resources can be synchronized or used in
read-only manner or shared values can be stored in a database table. The single threaded model can adversely
affect performance.


What is the difference between HttpServlet and GenericServlet?


GenericServlet:
A GenericServlet has a service() method to
handle requests

Protocol independent.

HttpServlet :

The HttpServlet extends GenericServlet and adds support for HTTP
protocol based methods like doGet(), doPost(), doHead() etc.

Protocol dependent.

What are the ServletContext and ServletConfig objects? What are Servlet environment objects?


ServletConfig :

The ServletConfig parameters are for a particular Servlet.
The parameters are specified in the web.xml (ie
deployment descriptor).

ServletContext :


The ServletContext parameters are specified for the entire Web
application. The parameters are specified in the web.xml (ie
deployment descriptor).

What is the difference between doGet () and doPost () or GET and POST?


doGet ():

The request parameters are transmitted as a query string
appended to the request. Allows browser bookmarks but not
appropriate for transmitting private or sensitive information.
http://MyServer/MyServlet?name=paul
This is a security risk.

GET was originally intended for static resource retrieval.


GET is not appropriate when large amounts of input data are
being transferred.

doPost():


The request parameters are passed with the body of the
request.
More secured.


POST was intended for input data submits where the results
are expected to change.