/** * Closes connections that have been idle for at least the given amount of time. * * @param idleTime the minimum idle time, in milliseconds, for connections to be closed */ public void closeIdleConnections(final long idleTime) { // the latest time for which connections will be closed final long idleTimeout = System.currentTimeMillis() - idleTime; if (log.isDebugEnabled()) { log.debug("Checking for connections, idle timeout: " + idleTimeout); } for (final Entry<HttpConnection, TimeValues> entry : connectionToTimes.entrySet()) { final HttpConnection conn = entry.getKey(); final TimeValues times = entry.getValue(); final long connectionTime = times.timeAdded; if (connectionTime <= idleTimeout) { if (log.isDebugEnabled()) { log.debug("Closing idle connection, connection time: " + connectionTime); } try { conn.close(); } catch (final IOException ex) { log.debug("I/O error closing connection", ex); } } } }
/** * Registers the given connection with this handler. The connection will be held until {@link * #remove} or {@link #closeIdleConnections} is called. * * @param connection the connection to add * @see #remove */ public void add(final HttpConnection connection, final long validDuration, final TimeUnit unit) { final long timeAdded = System.currentTimeMillis(); if (log.isDebugEnabled()) { log.debug("Adding connection at: " + timeAdded); } connectionToTimes.put(connection, new TimeValues(timeAdded, validDuration, unit)); }
/** * Removes the given connection from the list of connections to be closed when idle. This will * return true if the connection is still valid, and false if the connection should be considered * expired and not used. * * @param connection * @return True if the connection is still valid. */ public boolean remove(final HttpConnection connection) { final TimeValues times = connectionToTimes.remove(connection); if (times == null) { log.warn("Removing a connection that never existed!"); return true; } else { return System.currentTimeMillis() <= times.timeExpires; } }
public void closeExpiredConnections() { final long now = System.currentTimeMillis(); if (log.isDebugEnabled()) { log.debug("Checking for expired connections, now: " + now); } for (final Entry<HttpConnection, TimeValues> entry : connectionToTimes.entrySet()) { final HttpConnection conn = entry.getKey(); final TimeValues times = entry.getValue(); if (times.timeExpires <= now) { if (log.isDebugEnabled()) { log.debug("Closing connection, expired @: " + times.timeExpires); } try { conn.close(); } catch (final IOException ex) { log.debug("I/O error closing connection", ex); } } } }