> > If the connection is available for more than one request 
> > depends on the way the container handles threads. If each 
> > request is a new Thread you will win nothing. 
> > Instead you will loose performace as each request
> > would create a new connection to the database.
> 
> Yes that is true, there for we've thought of a way to have 
> the ThreadLocal get its connection from a pool. 

The notion of binding a Connection to a particular Thread using a
ThreadLocal is a pretty good idea.  The big advantage to my mind is that you
can use the Connection from any level of the call tree without passing it
around as a parameter.  What you need to keep in mind is that you must reset
the ThreadLocal before the Thread leaves your control.  In other words:

- At the beginning of your processing, check out a Connection from a
connection pool and bind it to the ThreadLocal.
- Throughout processing, the ThreadLocal can be used to obtain access to the
Connection.
- At the end of your processing, close the connection (which returns it to
the connection pool) and reset the ThreadLocal.

If you need to maintain database state across multiple HTTP requests, a
slight modification is needed:  before you check a Connection out from the
connection pool, look in the HttpSession to see whether there is a
Connection there already.  If there is, bind that Connection to the
ThreadLocal.  Otherwise, obtain a new Connection and put it both in the
HttpSession and in the ThreadLocal.

In the context of servlets, one good way to structure this would be to
create a ServletWithConnection class (extending HttpServlet), and have its
service() method
look something like this:

protected static ThreadLocal tl = new ThreadLocal();
protected void service (......) {
    Connection conn = connPool.getConnection();
    tl.set(conn);
    super.service();
    tl.set(null);
    conn.close();
}

Then you can extend this servlet whenever you need a database connection,
override doGet, doPost, whatever, as normal, and access the Connection via
tl.get() whenever you need it.

Incidentally, Martin Fowler talks about this in his new book on enterprise
architecture patterns -- look at the "registry" pattern.

http://search.barnesandnoble.com/booksearch/isbnInquiry.asp?isbn=0321127420

Cheers,

bn

--
To unsubscribe, e-mail:   <mailto:tomcat-user-unsubscribe@;jakarta.apache.org>
For additional commands, e-mail: <mailto:tomcat-user-help@;jakarta.apache.org>

Reply via email to