With every user trying to log in, our login Servlet will issue a call
to this validateUser method. Every call to validateUser method will
result in establishing a separate connection with the database. This
is definitely not the best approach. A few problems with this approach:
Every user trying to log in 'waits' for a connection to be
established with the database.
There is an overhead with opening and closing the connection with
every request.
We are not checking conditions such as 'if the no. of allowed
connections is over'. Such a condition will result into our
validateUser method not getting a valid connection.
These types of problems are easily solved with the use of a connection
pool. The basic idea of a connection pool is:
It is a 'collection' of open 'connections' with the database.
The connectionPool object when instantiated will open a predefined
no. of connections (say 10 ) with the database.
It will have methods like getConnection that will return a
reference to one of these 'already established' connections.
Similarly a returnConnection method will return the connection
back to the pool.
A Servlet will instantiate this connectionPool in its 'init' method.
Note that the init method is executed only once - when the servlet
is loaded.
The doPost and other methods will call the getConnection method,
use this connection to send and receive data (SQL and result)
over this connection.
The connectionPool will keep track of returned and 'in use'
connections.
This type of a connection pool will solve a lot of our performance
problems but there are still a few more things to be considered:
The Servlet by its very nature is executed in a multithreaded
environment. The use of such a connection pool should be made
'thread safe', (One simple way is to 'synchronize' the
getConnection method).
We will need to consider conditions such as 'stale connections'.
This serves as one of the basic needs to use an application server.
Imagine an application server that will take care of all of these
issues discussed! More over it can support a connection pool over
the whole application and not just one Servlet.
There are some other features common with many application servers,
such as:
Load Balancing: Ability to balance load with multiple servers.
EJB Support (component management): - Support for J2EE - EJB
standard.
The bottom line is: a good application server will 'shield' the
application programmer from many of these technical issues.
Click here to
Explore the World of Application Servers.