Phate
Phate

Reputation: 6622

Share connection pool among servlets

I'd like to share a database connection among servlets.

I created the connection pool and I obtain the dataSource object like this

Context envContext  = (Context)context.lookup("java:/comp/env");
dataSource = (DataSource)envContext.lookup("jdbc/limedb");

Now, I'd like to share this dataSource object among servlet so that each servlet can just do

connection = dataSource.getConnection();

to get its own connection.

What is the best method to achieve this? I'd like to create the pool at the application startup and store it somewhere...

Upvotes: 0

Views: 186

Answers (1)

Kurt Du Bois
Kurt Du Bois

Reputation: 7665

There are actually a few ways you can do this.

  1. You can use a dependency injection framework to manage those connections for you. Behind the scenes it will use an object pool.
  2. You can create a singleton object that manages an object pool containing datasources for you.
  3. You can write a singleton containing the code that returns the connection for you, so you don't have to know you are using a datasource.

It all depends on the use case, how familiar you are with java, the overall design of your application, etc.

Upvotes: 1

Related Questions