I know, if you use servlets, you can rely upon the container (Tomcat, etc.) to do connection pooling. But I want to write library objects that can be
used both in servlets and in stand alone utility programs. So far, that means I have to write a connection pool for when there is no container.
At first, I thought that I'd keep a Map of Connections that I hand out, and return them to the available pool when the Connection is returned. But I can't figure out what to use as the key to the Map, as the Connection is not immutable and I can't be sure that the hashCode() of the Connection is constant.
There is IdentityHashMap, it seems to fit your needs quite well.
I'd consider creating an interface with methods to obtain and close the connection. Users of your library would then provide implementation through which your library would manipulate the connections (I'm sure there is some design pattern which corresponds to this setup). Or better yet, let every method in your library which needs it accept a connection as a parameter, that way the caller can decide in which context (eg. as part of a wider transaction, or with specific isolation level) does he want your method to be executed.
Why not use a Set instead of a Map? I don't see the need for a key at all. If you make sure that no two Connections are equal, by not implementing the equals() method, then you shouldn't run into any problems. Or am I missing something?
Of course, many (most?) Set implementations are simply wrappers on Map, with no values stored. It "wastes" one reference per entry, which is nearly always trivial, and it allows one set of code to do two functions.