Reputation: 82
I encountered a question where in we have a set of say DB connections and multiple users simultaneously request for them.
I must be able to provide them the Conn object from a pool of existing connectios, and once they are done using it, put it back into the same pool of available connections.
The approach I could think of was to have 2 sets for each used and unused connections and keep moving objects back and forth.
I am somehow not convinced it's the best way to do this.
Can anyone pls suggest a nicer approach? I was wondering if we could mark the connection obj as in use or something so that we can do away with these two sets?
Upvotes: 0
Views: 73
Reputation: 61128
There are thousands of implementations to choose from:
These pools are tested, working, optimised code. Not whatever your homebrew solution is.
The problem you encountered is just one you will encounter on the way to writing a resilient connection pool. The solution you propose is naive at best. There are many other issues, from the misuse of the pool to connection dropout that you have to handle. And not only that but the code must be threadsafe.
For general scarce resource pooling, not JDBC connections, use Commons Pool. Again, this is tested, working code.
Upvotes: 1
Reputation: 25950
Don't reinvent the wheel. There are existing solutions for this, one of them being Apache Commons pools : https://commons.apache.org/proper/commons-pool/. All you have to do is provide a factory to initialize your connections at the beginning, then Apache will provide you with a GenericObjectPool
(see doc) on which you can call borrowObject
before accessing a connection in the pool and then release it using returnObject
.
Upvotes: 0