How to use connection pool using service locator design Pattern in java

In this post, you will learn about the Connection Pool. This post is intended by java application development experts for entire development community to let people learn and acknowledge about Connection Pool and how to use its object using Service Locator design pattern.

Introduction

Connection pool is a mechanism which applicable for all technologies in the world. We can use tomcat server to configure the connection pool and we should use Service locator design pattern for better connection pool performance.

What is connection pool? 

Connection pool is mechanism which avoids to creating new connection with Database for each client request which is coming from Application. Connecting with DB via programming is too expensive. There are many configurable connection pool mechanism in Java. Using connection pool mechanism we can maintain connection object in-memory. Whenever connection object is required, we can reuse the available connection from the pool of memory, instead of creating new connection unless all connection are occupied by the application. This article demonstrate how to configure connection pool in Apache Tomcat server and how to use those connection pool object using Service Locator design pattern.

What is Service Locator design pattern? 

Service locator is a J2EE design pattern which tells how to interact with reusable business component which used in across the Application. For example, once you configured the connection pool in tomcat server, all available connection are available in Tomcat server in memory.

How do you get DB connection from the pool for your application? 

There are many of ways to get the DB connection which configured in Tomcat Server. The best way is Service Locator design pattern. If want to create a Java class which should have service locator behavior, your class must follow following.
• Your class constructor must be private
• Your class should have static method which return a connection object and delegates to client.
The responsibility of private constructor is to create necessary service which used by application. In our example service locator creates the DBconnection and make it available in the in-memory.

Responsibility of static method is to give the services to client application which created by private constructor.
Following are the configuration and code implementation of creating Connection pool.
DB connection and connection pool configuration in Tomcat server.
<resource auth="Container" driverclassname="com.mysql.jdbc.Driver" maxactive="10" maxidle="4" name="jdbc/connectionTest" password="suresh123" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/test" username="suresh">
In order to configure DB connection in tomcat server, open conf/context.xml and add above resource tag. Apply mysql connection properties as in above xml code. Configure maximum active connection and idle connection pool. In the above example 10 is maximum connection pool and idle is 4. To get this connection object in you java program, you need to create Service locator java class which used globally in your application. Wherever dB connection is need, the Service locator provide the connection object from java in-memory.
Following is static variable in Service Locator class private static Connection connection; Following is a private constructor which create Datasource using lookup method. In this example our datasource name is “jdbc/connectionTest”
private ConnectionPoolService() {

try{

Context initContext = new InitialContext();
Context envContext =(Context)initContext.lookup("java:/comp/env");
DataSource dataSource =(DataSource)envContext.lookup("jdbc/connectionTest");
connection = dataSource.getConnection();
} catch (NamingException e) {
e.printStackTrace();
}catch(Exception ex){
ex.printStackTrace();
}
}
jdbc/connectionTest is datasource name configured in conf/context.xml file, the lookup method successfully find the datasource name, it will assign to DataSource object. Using Datasource object,we can get the connection object. The above particular code should execute only once in the application because, the same connection object should use wherever db connection required. The entire code is placed in private constructor which means we can’t call this constructor in outside of the class.
public static Connection getConnection() {
 if(connection == null) {
  new ConnectionPoolService();
 }
 return connection; 
}
The above method is a static method which returns the connection object. This method invokes the private constructor and creates the connection object. According to this method code, whenever invoke this method, first check the connection object availability. If connection object is not available, it invokes the private constructor to create new connection object. If connection object is already available, this method doesn’t invoke the private constructor instead it will return the available existing connection from the java in-memory. Through this way we can avoid the initializing new connection object for each DBs connection request.
The below code demonstrates that how to get connection object from ConnectionPoolService.
public Customer getCustomerData(long customerId) throws MyDAOException {
  Connection connection = null;
  Customer customer = null;
  try {
    ResultSet resultSet = null; 
   connection = ConnectionPoolService.getConnection();
   Statement statement = connection.createStatement();
   String query = "SELECT * FROM customer where customer_id=" + customerId; 
   resultSet = statement.executeQuery(query);
   customer = new Customer();
   while (resultSet.next()) { 
    customer.setCustomerId(Long.parseLong(resultSet.getString(1)));
    customer.setCustomerName(resultSet.getString(2));
    customer.setEmailId(resultSet.getString(3));
   }
   
  }catch(Exception ex){
   ex.printStackTrace();
   throw new MyDAOException("Error while connecting db");
  }
                finally
               {
                    resultSet.close();
                    connection.close();  
               }
  return customer;
}
The above method invokes the following line which returns the connection object.
connection = ConnectionPoolService.getConnection();
This method either directly returns connection from the java in-memory or creates the new connection based on availability of connection object.

Conclusion 

Service locator is a J2EE Design pattern which use the concept of Java singleton design pattern. The use of singleton design pattern is to create a java object only once and used in across the application. In our case private constructor create connection object only once. If connection is already available, it reused by the application. Why it is called as Service locator? If private constructor creates only java instance, we can say it is singleton design pattern but the private constructor creating DB resource which is being serviced across the application so, it is called as Service Locator design pattern

Below diagram explains how service locator works to get connection pool object from the tomcat server.
Using service locator mechanism you can adopt this code for any service you want to pick from particular source.

Hope you have understood the use of Connection Pool object with Service locator design pattern in java application development. For any confusion, ask expert assistance.

Bio:- Aaron Jacobson is expertise in java application development. He has been working as a java developers in Technoligent for many years. He major contribute included the collection of web solutions like java, Python, Asp.Net, Mobile Apps etc…. He has extensive experience in java technology and object oriented programming language. You can follow me on twitter@Techno_Ligent and you can add friend on Facebook @TechnoLigent
 

Java tutorial for beginners Copyright © 2012