Should I close the connection obtained from the DataSource manually?

When I get Connection from a DataSource , do I have to close it manually? I mean, if I have to close it, how will it be used in future requests?

+6
source share
2 answers

A compound obtained from a pool of compounds should be used in the same way as a regular compound. The JDBC 4.2 specification (section 11.1) talks about the pool:

When an application is terminated using a connection, it closes the logical connection using the Connection.close method . This closes the logical connection, but does not close the physical connection. Instead, the physical connection is returned to the pool so that it can be reused.

The connection pool is completely transparent to the client: the client receives the unified connection and uses it the same way as it does , but uses a non-unified connection .

(my emphasis)

This means that when you end the connection, you always call Connection.close() ! It does not matter if this is a physical connection or a logical connection from a pool.

The reason is that the connection is a physical (direct) connection, or the logical connection should be purely a configuration issue, and not an application code problem that simply uses the connection.

In the case of the connection pool, the close() data will be different, and some implementations in this case are ineffective - the logical connection and the signal in the connection pool that the basic physical connection is reusable are invalid. A connection pool can perform some validation checks and then return the (physical) connection to the pool or close it (for example, if the pool has too many connection downtimes or too old connections, etc.).

The close() call is not only resolved, it is even vital for the connection pool to function properly. Calling close() usually requires some auxiliary line to close (restore) logical connections that have been used for too long. Since this timeout is usually longer than the normal needs of the application, it can lead to exhaustion of the pool or configuration when the pool requires a higher maximum number of connections than is really necessary.

+8
source

You need to close Connection in order to return it to the pool, the next time you request a Datasource.getConnection() connection from the pool, you will get. There is no problem. Sometimes you do not want to close the connection after each operation and use the same connection for several operations. In this case, you should not close it until the last operation is completed.

+1
source

Source: https://habr.com/ru/post/970094/


All Articles