user2514421 user2514421 - 6 months ago 41
Java Question

Jdbc data pooling

I have a problem in understanding How exactly data source object is different from normal connection.I know that using data source we can resue the connection all over the class where we writing our sql queries.As far i know for small standalone applications if we create one connection object which is private or public we can resuse that object any where same with data source once object is created we can re-use that object just like connection object... then how's different? why we need to use data source obj then?


DataSource is most commonly used in webapps, where your code needs a database Connection for the duration of the web request processing.

The DataSource is configured for the webapp server, and can then be used by your code to get a new Connection, without your code needing to know the details (e.g. URL, user, password).

Since creating a connection to a database is a slow operation, rather than closing the connection when your code is done with it, the connection is stored in a pool. When your code then processes another web request, it can get that connection from the pool instantly, gaining a huge boost in performance.

To summarize, the DataSource has two purposes: Removing configuration from your code, and supporting reuse through pooling.

For a small standalone single-threaded application, where the connection is created at startup and just used while the program is running, there is nothing gained by using a DataSource. Using DriverManager is easier for such programs.