-2

I need to create a custom connection pool in Java in such a way that if a user asks for connection and after using it returns to pool but he can maintain a reference to the connection by assigning it to some variable.

Since he has returned connection to pool I can give that to any other user. Now two users will be having the same connection object which is wrong.

How can I create a connection pool by avoiding such scenario?

This question is asked in an interview. I know there are many libraries are available which provide this functionality but how internally they work to achieve this.

  • Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer. Whole books and tutorials are written about such topics; and people spend a **lot** of time implementing that. Chances are close to 0 that such a topic fits into one SO question/answer. – GhostCat Apr 24 '17 at 13:19
  • It is also quite strange to have such a requirements. If a user returns a connection to the pool (usually by calling `close()`), he shouldn't be able to use it any more – this would be a bug in the client code. You can quite easily prevent this by using a connection wrapper with an internal `closed` flag that prevents any call after calling `close()`. But this is standard stuff for the many implementations out there, no need to reinvent the wheel. – Didier L Apr 24 '17 at 14:19
  • The solution is to use PhantomReference to the client proxy (this is a more efficient alternative to a `finalizer`). When the proxy is collected, the notification to the pool allows it to reclaim the connection and make it available to others. See this [article](http://www.kdgregory.com/index.php?page=java.refobj) for a thorough explanation. – Ben Manes Apr 25 '17 at 19:46

1 Answers1

0

It looks like you're describing a feature of UCP (Universal Connection Pool) called connection labeling. You might want to look into the doc.

Jean de Lavarene
  • 3,461
  • 1
  • 20
  • 28