Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java servlets and database connection pooling

Just looking at examples of connection pooling on the web, they all implement connection pooling on a per servlet basis. So each servlet has its own pool of database connections. My question is, why is that preferable to something like a global pool of db connections? Since a global pool is seems more efficient than a per servlet pool..

Also, since I'm thinking about implementing such a pool. Is there a way to have a class initialized before the servlets(I'm using jetty btw)? I'm just starting servlet development but that would seem useful for other things too like configuration. Otherwise I was just going to use some sort of singleton like pattern..

like image 634
Ari Ronen Avatar asked Dec 07 '22 05:12

Ari Ronen


2 Answers

1) I'd say that standard practice is to set up a connection pool as a JNDI resource in the context descriptor, which would not be a per-servlet thing to do.

2) You'll want to implement and declare a ServletContextListener.

like image 71
Jonathan Feinberg Avatar answered Dec 18 '22 16:12

Jonathan Feinberg


To be honest, I don't really know what you are talking about. Maybe you could provide the samples you looked at.

To me, a "real" connection pool should be totally Servlet agnostic and using a connection pool on a per Servlet basis is a more a usage detail (and a bad one IMO). Just look at DBCP or c3p0 for good examples of connection pools that you may use in an "out-of-container" context.

Also note that most (if not all) containers actually provide their own connection pool implementations (sometime based on the previous mentioned examples) and I don't see any good reason to not use them. The standard way to use them is to get a DataSource registered with a JDNI naming service. Today, the DataSouce is most of time injected through IoC. In old days, the Service Locator pattern was often used.

In the case of Jetty, have a look at DataSource Examples in the documentation.

like image 27
Pascal Thivent Avatar answered Dec 18 '22 17:12

Pascal Thivent