Nearby lessons

23 of 37

JDBC - Connection Pooling

📌 What You Will Learn
  • 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.

In simple words: A connection pool keeps ready connections so you borrow one, use it, and return it. The connection is never destroyed, so the next query skips all the expensive setup.

Benefits: much faster (no repeated setup), and the database has fewer connections open (no exhaustion).

Example02
Loading editor…

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.

Trainer's Note: Updated knowledge: in real projects you will almost never write DriverManager.getConnection(...) repeatedly. Instead, a connection pool (HikariCP, Apache DBCP, C3P0) manages connections behind a DataSource. Spring Boot even sets this up automatically. The concept — borrow, use, return — is the important thing to remember.
Example03
Loading editor…
📝 Key Takeaways
  • 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.

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.