Nearby lessons
23 of 37JDBC - Connection Pooling
- Why creating a new connection every time is expensive
- What connection pooling is and how it solves the problem
- The modern DataSource approach
- Keeping database settings in a Properties file
Connection Pooling is a fundamental part of database programming with JDBC. This lesson explains The Problem — Connections Are Expensive, What is Connection Pooling? and The Modern Way — DataSource with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
The Problem — Connections Are Expensive
Creating a database connection involves: loading the driver, opening a network channel, the database verifying the username and password, and allocating memory. Doing this for every single query is slow.
Imagine opening a new shop door every time a customer wants to enter — ridiculous. A shop has one door kept open and customers use it again and again. Connection pooling does exactly that.
What is Connection Pooling?
Connection pooling means keeping a pool (a set) of ready connections alive. When the application needs a connection, it borrows one from the pool; when finished, it returns it to the pool — it is not destroyed.
Benefits: much faster (no repeated setup), and the database has fewer connections open (no exhaustion).
The Modern Way — DataSource
The modern JDBC way is the DataSource interface (javax.sql.DataSource). A DataSource object holds the database settings and hands out connections — and it can work together with a connection pool.
- Creating a connection each time is slow; pooling reuses ready connections.
- Pool = borrow a connection, use it, return it — never destroy it.
- DataSource is the modern replacement for DriverManager, often backed by a pool.
- Properties file keeps DB settings outside the code; edit it without recompiling.
- Use Properties.load() + getProperty() to read settings.
- Keep real passwords out of public repos.