Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
502
Chapter 18 JDBC and Database Connection Pooling
connection pool from its
init
method, and you should be sure
that the servlet is initialized prior to a real client request. The
following code uses vectors to store available idle connections
and unavailable, busy connections. Assume that
makeNew
Connection
uses a URL, username, and password stored previ
ously, then simply calls the
getConnection
method of
DriverManager
.
availableConnections = new Vector(initialConnections);
busyConnections = new Vector();
for(int i=0; i
availableConnections.addElement(makeNewConnection());
}
2. Manage available connections.
If a connection is required and an idle connection is available,
put it in the list of busy connections and then return it. The busy
list is used to check limits on the total number of connections as
well as when the pool is instructed to explicitly close all connec
tions. One caveat: connections can time out, so before returning
the connection, confirm that it is still open. If not, discard the
connection and repeat the process. Discarding a connection
opens up a slot that can be used by processes that needed a con
nection when the connection limit had been reached, so use
notifyAll
to tell all waiting threads to wake up and see if they
can proceed (e.g., by allocating a new connection).
public synchronized Connection getConnection()
throws SQLException {
if (!availableConnections.isEmpty()) {
Connection existingConnection =
(Connection)availableConnections.lastElement();
int lastIndex = availableConnections.size() 1;
availableConnections.removeElementAt(lastIndex);
if (existingConnection.isClosed()) {
notifyAll(); // Freed up a spot for anybody waiting.
return(getConnection()); // Repeat process.
} else {
busyConnections.addElement(existingConnection);
return(existingConnection);
}
}
}
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved