Domanda

I understand that finalizers are a bad thing to use, even for connection closing (Is closing the connection in finalize best practice?), since they are not guaranteed to be called. But what if your connections are pooled via a connection pool? In my case, I'm using Apache Commons pool (http://commons.apache.org/proper/commons-pool/) to pool SFTP connections. I can't use the try-with-resources technique because each connection should not be closed at the end of every try (so that it can be potentially re-used by the pool for the next action).

I do provide a closePool() method that calls pool.close() so that whatever programmer uses my code can call it, but what if she/he forgets to do so? Is calling this method from a finalizer the best solution to try and close the connection pool in case it's not done manually, or is there a better way? Would a shutdown hook work better for this?

È stato utile?

Soluzione

If you are writing a library that provides this functionality to someone else, I don't really see what else you can do besides providing a closePool() method. You could perhaps have your classes inherit from java.io.Closeable and/or AutoCloseable, but other than advertising the need to clean up your resources, you mostly have to rely on the developers using your code to do the right thing.

Unexpected finalizers inside library code could be a nasty thing to run into if they aren't implemented correctly.

You could try to add a shutdown hook, but if the JVM is shutting down anyway then there isn't much of a point in forcibly closing the connection pool at that point.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top