Using a connection pool to improve the efficiency of servlet database access (1)

Source: Internet
Author: User
Tags time in milliseconds

As the preferred server-side data processing technology, Java Servlet is rapidly replacing CGI scripts. One of the advantages of servlet over CGI is that not only can multiple requests share public resources, but also can retain continuous data between different user requests. This article introduces a practical technology that gives full play to this feature, that is, the database connection pool.

I. Significance of implementing the connection pool

Dynamic Web sites often use the information stored in the database to generate Web pages. Each page request leads to a database access. Connecting to a database requires a certain amount of communication and memory resources, as well as user authentication and security context configuration. Therefore, it is often the most time-consuming operation. Of course, the actual connection time overhead is ever-changing, but the delay between 1 and 2 seconds is not uncommon. If a database-based Web application only needs to establish an initial connection
When different page requests share the same connection, the performance can be significantly improved.
Servlet is a Java class. Servlet Engine (it may be part of web service software or an independent additional module) when the system starts or the servlet is requested for the first time, load the class into the Java Virtual Machine and create an instance of the servlet. Different user requests are processed by multiple independent threads of the same servlet instance. Those
Data that is continuously valid between different requests can be saved using Servlet instance variables or independent auxiliary objects.
To access a database using JDBC, you must first create a connection with the database to obtain a connection object. The connection object provides the method for executing SQL statements.
The database connection pool described in this article includes a management class dbconnectionmanager that provides interfaces with multiple connection pool objects (dbconnectionpool class. Each connection pool object manages a set of JDBC connection objects, and each connection object can be shared by any number of servlets.
Dbconnectionpool provides the following functions:

1) Obtain (or create) available connections from the connection pool.
2) return the connection to the connection pool.
3) release all resources and close all connections when the system is shut down.

In addition, the dbconnectionpool class can also handle invalid connections (originally registered as available connections are no longer available for some reason, such as timeout and communication problems)
And the total number of connections in the connection pool cannot exceed a certain predefined value.
Management class dbconnectionmanager is used to manage multiple connection pool objects. It provides the following functions:

1) load and register the JDBC driverProgram.
2) create a connection pool object based on the attributes defined in the property file.
3) ing between the connection pool name and its instance.
4) tracking the client program's reference to the connection pool to ensure that all connection pools are safely closed when the last client program ends.

The remaining part of this article will detail these two classes. Finally, an example is provided to demonstrate the general process of using the connection pool of servlet.

II. Specific implementation

The list of dbconnectionmanager. Java programs is as follows:

001 import java. Io .*;
002 import java. SQL .*;
003 import java. util .*;
004 import java. util. date;
005
006 /**
007 * management class dbconnectionmanager supports connection to one or more databases defined by attribute files
008 * pool access. The client program can call the getinstance () method to access the unique instance of this class.
009 */
010 public class dbconnectionmanager {
011 static private dbconnectionmanager instance; // unique instance
012 static private int clients;
013
014 private vector drivers = new vector ();
015 private printwriter log;
016 private hashtable pools = new hashtable ();
017
018 /**
019 * a unique instance is returned. If this method is called for the first time, an instance is created.
020 *
021 * @ return dbconnectionmanager unique instance
022 */
023 static synchronized public dbconnectionmanager getinstance (){
024 if (instance = NULL ){
025 instance = new dbconnectionmanager ();
026}
027 clients ++;
028 return instance;
029}
030
031 /**
032 * construct a private function to prevent other objects from creating this class instance
033 */
034 private dbconnectionmanager (){
035 Init ();
036}
037
038 /**
039 * return the connection object to the connection pool specified by the name
040 *
041 * @ Param name the connection pool name defined in the property File
042 * @ Param con connection object
043 */
044 public void freeconnection (string name, connection con ){
045 dbconnectionpool pool = (dbconnectionpool) pools. Get (name );
046 if (pool! = NULL ){
047 pool. freeconnection (CON );
048}
049}
050
051 /**
052 * obtain an available (idle) connection. If there is no available connection and the number of existing connections is less than the maximum number of connections
053 * limit, a new connection is created and returned.
054 *
055 * @ Param name the connection pool name defined in the property File
056 * @ return connection available connection or null
057 */
058 public connection getconnection (string name ){
059 dbconnectionpool pool = (dbconnectionpool) pools. Get (name );
060 if (pool! = NULL ){
061 return pool. getconnection ();
062}
063 return NULL;
064}
065
066 /**
067 * obtain an available connection. If no available connection is available and the number of existing connections is smaller than the maximum number of connections,
068 * is created and a new connection is returned. Otherwise, wait for other threads to release the connection within the specified time.
069 *
070 * @ Param name connection pool name
071 * @ Param time wait time in milliseconds
072 * @ return connection available connection or null
073 */
074 public connection getconnection (string name, long time ){
075 dbconnectionpool pool = (dbconnectionpool) pools. Get (name );
076 if (pool! = NULL ){
077 return pool. getconnection (time );
078}
079 return NULL;
080}
081
082 /**
083 * close all connections and cancel driver registration
084 */
085 public synchronized void release (){
086 // wait until the last client program calls
087 if (-- clients! = 0 ){
088 return;
089}
090
091 enumeration allpools = pools. Elements ();
092 while (allpools. hasmoreelements ()){
093 dbconnectionpool pool = (dbconnectionpool) allpools. nextelement ();
094 pool. Release ();
095}
096 enumeration alldrivers = drivers. Elements ();
097 while (alldrivers. hasmoreelements ()){
098 driver = (driver) alldrivers. nextelement ();
099 try {
100 drivermanager. deregisterdriver (driver );
101 log ("revoking JDBC driver" + driver. getclass (). getname () + "Registration ");
102}
103 catch (sqlexception e ){
104 log (E, "Registration of the following JDBC driver cannot be revoked:" + driver. getclass (). getname ());
105}
106}
107}
108
109 /**
110 * create a connection pool instance based on the specified attributes.
111 *
112 * @ Param props connection pool attributes
113 */
114 private void createpools (properties props ){
115 enumeration propnames = props. propertynames ();
116 while (propnames. hasmoreelements ()){
117 string name = (string) propnames. nextelement ();
118 If (name. endswith (". url ")){
119 string poolname = Name. substring (0, name. lastindexof ("."));
120 string url = props. getproperty (poolname + ". url ");
121 If (url = NULL ){
122 log ("not specified URL for connection pool" + poolname + ");
123 continue;
124}
125 string user = props. getproperty (poolname + ". User ");
126 string Password = props. getproperty (poolname + ". Password ");
127 string maxconn = props. getproperty (poolname + ". maxconn", "0 ");
128 int Max;
129 try {
130 max = integer. valueof (maxconn). intvalue ();
131}
132 catch (numberformatexception e ){
133 log ("Maximum number of wrong connections limit:" + maxconn + ". Connection Pool:" + poolname );
134 max = 0;
135}
136 dbconnectionpool =
137 new dbconnectionpool (poolname, URL, user, password, max );
138 pools. Put (poolname, pool );
139 log ("successfully created connection pool" + poolname );
140}
141}
142}
143
144 /**
145 * initialize the read attribute
146 */
147 private void Init (){
148 inputstream is = getclass (). getresourceasstream ("/DB. properties ");
149 properties dbprops = new properties ();
150 try {
151 dbprops. Load (is );
152}
153 catch (exception e ){
154 system. Err. println ("attribute files cannot be read." +
155 "make sure that dB. properties is in the path specified by classpath ");
156 return;
157}
158 string logfile = dbprops. getproperty ("logfile", "dbconnectionmanager. log ");
159 try {
160 log = new printwriter (New filewriter (logfile, true), true );
161}
162 catch (ioexception e ){
163 system. Err. println ("log file cannot be opened:" + logfile );
164 log = new printwriter (system. Err );
165}
166 loaddrivers (dbprops );
167 createpools (dbprops );
168}
169
170 /**
171 * load and register all JDBC drivers
172 *
173 * @ Param props attributes
174 */
175 private void loaddrivers (properties props ){
176 string driverclasses = props. getproperty ("drivers ");
177 stringtokenizer ST = new stringtokenizer (driverclasses );
178 while (St. hasmoreelements ()){
179 string driverclassname = ST. nexttoken (). Trim ();
180 try {
181 driver = (driver)
182 class. forname (driverclassname). newinstance ();
183 drivermanager. registerdriver (driver );
184 drivers. addelement (driver );
185 log ("successfully registered JDBC driver" + driverclassname );
186}
187 catch (exception e ){
188 log ("unable to register JDBC driver:" +
189 driverclassname + ", error:" + E );
190}
191}
192}
193
194 /**
195 * write text information to the log file
196 */
197 private void log (string MSG ){
198 log. println (new date () + ":" + MSG );
199}
200
201 /**
202 * write text information and exceptions to log files
203 */
204 private void log (throwable E, string MSG ){
205 log. println (new date () + ":" + MSG );
206 E. printstacktrace (log );
207}
208
209 /**
210 * this internal class defines a connection pool. It can create new connections as required until the predefined
211 * the maximum number of connections. It can verify the connection validity before returning the connection to the client program.
212 */
213 class dbconnectionpool {
214 private int checkedout;
215 private vector freeconnections = new vector ();
216 private int maxconn;
217 private string name;
218 private string password;
219 private string URL;
220 private string user;
221
222 /**
223 * Create a new connection pool
224 *
225 * @ Param name connection pool name
226 * @ Param url jdbc url of the database
227 * @ Param user database account, or null
228 * @ Param Password, or null
229 * @ Param maxconn the maximum number of connections allowed in the connection pool
230 */
231 public dbconnectionpool (string name, string URL, string user, string password,
232 int maxconn ){
233 this. Name = Name;
234 this. url = URL;
235 This. User = user;
236 this. Password = password;
237 This. maxconn = maxconn;
238}
239
240 /**
241 * return unused connections to the connection pool
242 *
243 * @ Param con connection released by the client program
244 */
245 public synchronized void freeconnection (connection con ){
246 // Add the specified join to the end of the Vector
247 freeconnections. addelement (CON );
248 checkedout --;
249 notifyall ();
250}
251
252 /**
253 * obtain an available connection from the connection pool. If there is no idle connection and the current number of connections is less than the maximum number of connections
If the number limit is 254 *, a new connection is created. If the previously registered available connection is no longer valid, it is deleted from the vector,
255 * Then recursively call yourself to try a new available connection.
256 */
257 public synchronized connection getconnection (){
258 connection con = NULL;
259 If (freeconnections. Size ()> 0 ){
260 // obtain the first available connection in the vector
261 con = (connection) freeconnections. firstelement ();
262 freeconnections. removeelementat (0 );
263 try {
264 If (con. isclosed ()){
265 log ("deleting an invalid connection from the connection pool" + name + ");
266 // call yourself recursively and try to obtain available connections again
267 con = getconnection ();
268}
269}
270 catch (sqlexception e ){
271 log ("deleting an invalid connection from the connection pool" + name + ");
272 // call yourself recursively and try to obtain available connections again
273 con = getconnection ();
274}
275}
276 else if (maxconn = 0 | checkedout <maxconn ){
277 con = newconnection ();
278}
279 if (con! = NULL ){
280 checkedout ++;
281}
282 return con;
283}
284
285 /**
286 * obtain available connections from the connection pool. You can specify the maximum waiting time for the client program.
287 * See the previous getconnection () method.
288 *
289 * @ Param timeout wait time limit in milliseconds
290 */
291 public synchronized connection getconnection (long timeout ){
292 long starttime = new date (). gettime ();
293 connect con;
294 while (con = getconnection () = NULL ){
295 try {
296 wait (timeout );
297}
298 catch (interruptedexception e ){}
299 if (new date (). gettime ()-starttime)> = timeout ){
300 // wait () returns timeout
301 return NULL;
302}
303}
304 return con;
305}
306
307 /**
308 * close all connections
309 */
310 public synchronized void release (){
311 enumeration allconnections = freeconnections. Elements ();
312 while (allconnections. hasmoreelements ()){
313 connection con = (connection) allconnections. nextelement ();
314 try {
315 con. Close ();
316 log ("close a connection pool" + name + "in a connection pool ");
317}
318 catch (sqlexception e ){
319 log (E, "unable to close connection pool" + name + "connection ");
320}
321}
322 freeconnections. removeallelements ();
323}
324
325 /**
326 * Create a new connection
327 */
328 private connection newconnection (){
329 connection con = NULL;
330 try {
331 if (user = NULL ){
332 con = drivermanager. getconnection (URL );
333}
334 else {
335 con = drivermanager. getconnection (URL, user, password );
336}
337 log ("connection pool" + name + "Create a new connection ");
338}
339 catch (sqlexception e ){
340 log (E, "unable to create connections to the following urls:" + URL );
341 return NULL;
342}
343 return con;
344}
345}
346}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.