In my standalone app, generating over 1000 threads in single time and each thread has it's own Hibernate session. But in this case, count of sessions hits over database max connections restriction that throws an error.
I've tried to set .getCurrentSession()
instead of .openSession()
, but it brought no effect, because Hibernate opens new own session for each new thread anyway.
How can i round this problem? Can i set somehow the count of slots for concurrent connections? For e.g. pass 100 connections and let another 900 to wait till these 100 will be closed to process this further?
Using a connection pool can help solve this.
Here is a post about setting up a connection pool Can you only have one hibernate session per thread in java?
Most people utilize a connection pool, like C3P0 that can be used to ensure session reuse and speed up your code.
The best structure I use is to create a SessionFactory once in application launch, as this sets up the connection pool to the database. Then, utilizing maybe a singleton pattern to keep a single SessionFactory, request new sessions for each transaction you perform from the single SessionFactory. Hibernate will utilize the underlying connection pool to handle session reuse for speed and optimization.
Here is another post on various connection pooling libraries available.
By default, Hibernate ships with the ability to obtain a data source implementation ( javax.sql.DataSource ) from JNDI by setting the properties appropriately
hibernate default connection pooling
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With