Hibernate does it best to use a database connection as short as possible. Claiming a database connection when a session is opened goes against this (there are no queries available to perform, this will come later). A side effect would be that the pool is exhausted much sooner.
c3p0 uses a checkoutTimeout to determine how long to wait for a connection to become available when the pool is exhausted. By default this timeout is 0 (i.e. no timeout) but if it is set to another value (e.g. 50 000 milliseconds) and the timeout is reached, a SQLException
is thrown.
You can try to make an educated guess to see if the checkoutTimeout
will be reached before you start a transaction, but it will always be a guess: it depends on how fast the other transactions complete.
To make the guess you could use c3p0's JMX interface and get the values for the number of connections (NumConnections), the number of busy connections (NumBusyConnections) and the number of threads waiting for a connection (NumThreadsAwaitingCheckout).
If there are many busy connections and many threads are waiting, there is a good chance the checkoutTimeout
will be reached, but you'll have to determine the exact numbers via stress-testing.