Search code examples
javamultithreadingconnectionconnection-pooling

Under what conditions should I automatically pull Connection back to Connection Pool (Java)


I am trying to write code for a simple concurrent Connection Pool, using Java and Semaphores from java.util.concurrent. Everything is all right but while writing the daemon thread which should check all Connections from the pool which are in use, and pull them back to the pool if they are used longer than a certain IDLE_TIMEOUT, I banged against a problem. How can I understand that the connection had expired? That user just forgot to close it? At the moment my implementation uses a HashMap, where I put taken Connection with the System.currentTimeInMillis(), and then my daemon thread regularly checks that time not to exceed 5 seconds. But what if user needs that Connection for the time longer than 5 sec.? So, I need at least an idea of better approach. Any links, materials, pieces of advice are appreciated.


Solution

  • You could give the user a choice of connections for instance AutomaticConnection, LongRunningConnection, UnmanagedConnection. The AutomaticConnection could perhaps work like your current connection closing them after a default amount of time. For the LongRunningConnection you could make the user provide a long indicating the number of miliseconds they expect to be using the connection before it being automatically closed. Finally for the UnmanagedConnectionthe users would have the responsibility of calling close themselves. Perhaps you could also reset the timer based on when the Connection's methods were called.