How connection pooling works in Java and JDBC
By: Ramlak in JDBC Tutorials on 2007-04-04
Connection pooling has become the standard for middleware database drivers. The process of creating a connection, always an expensive, time-consuming operation, is multiplied in these environments where a large number of users are accessing the database in short, unconnected operations. Creating connections over and over in these environments is simply too expensive. Here is a sample program for connection pooling using JDBC in Java application
import java.sql.*; import javax.sql.DataSource; import javax.naming.InitialContext; import javax.naming.NamingException; public class ConnectionPoolExample { private static final String DB_URL = "jdbc:mysql://localhost/mydatabase"; private static final String DB_USER = "myuser"; private static final String DB_PASSWORD = "mypassword"; private static final String JNDI_NAME = "java:comp/env/jdbc/myDataSource"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; DataSource ds = null; try { // Get the DataSource from JNDI InitialContext ctx = new InitialContext(); ds = (DataSource) ctx.lookup(JNDI_NAME); // Get a connection from the pool conn = ds.getConnection(); // Execute a query stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * FROM customers"); // Process the results while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); System.out.println(id + ", " + name + ", " + email); } } catch (SQLException e) { e.printStackTrace(); } catch (NamingException e) { e.printStackTrace(); } finally { // Close the resources try { if (rs != null) rs.close(); } catch (SQLException e) { } try { if (stmt != null) stmt.close(); } catch (SQLException e) { } try { if (conn != null) conn.close(); } catch (SQLException e) { } } } }
The transaction profile for Web applications, probably the most common application in use today, is that of a large number of users performing short, discrete database operations. These applications usually perform work centered around creating a web page that will be sent back to the user's browser. Transactions are generally short-lived, and user sessions are often limited in time.
A connection pool operates by performing the work of creating connections ahead of time, In the case of a JDBC connection pool, a pool of Connection objects is created at the time the application server (or some other server) starts. These objects are then managed by a pool manager that disperses connections as they are requested by clients and returns them to the pool when it determines the client is finished with the Connection object. A great deal of housekeeping is involved in managing these connections.
When the connection pool server starts, it creates a predetermined number of Connection objects. A client application would then perform a JNDI lookup to retrieve a reference to a DataSource object that implements the ConnectionPoolDataSource interface. The client application would not need make any special provisions to use the pooled data source; the code would be no different from code written for a nonpooled DataSource.
When the client application requests a connetion from the ConnetionPoolDataSource, the data source implementation would retrieve a physical connection to the client application. the ConnectionPoolDataSource would return a Connection object that implemented the PooledConnection interface.
The PooledConnection interface dictates the use of event listeners. These event listeners allow the connection pool manager to capture important connection events, such as attempts by the client application to close the connection. When the driver traps a close-connection event, it intercedes and performs a pseudo-close operation that merely takes the Connection object, returns it to the pool of available connection, and performs any housekeeping that is necessary.
The operation of the connection pool should be completely transparent to the client application. The triggering of connection events, the manipulation of the object pool, and the creation and destruction of physical connections are all managed by the pool manager. The activities of the connection pool are, however, configurable by the application developer or the application deployer
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Data Access Technologies in Java
JDBC and Tomcat context settings
TEXT datatype SPLIT in MSSQL - to solve the 8000 limit set by varchar
What is Referential Integrity in databases?
Handling CSV in Stored Procedures
java.lang.NoClassDefFoundError and java.lang.NoSuchMethodError
Calling a Stored Procedure from JDBC in Java
setSavepoint and releaseSavepoint Example in Java
Result Sets, Cursors and Transactions in SQL
Stored Procedures example in SQL
Using the DriverManager Class vs Using a DataSource Object for a connection
Comments