1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 package org.apache.commons.httpclient.util;
30
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.Map;
34
35 import org.apache.commons.httpclient.HttpConnection;
36 import org.apache.commons.logging.Log;
37 import org.apache.commons.logging.LogFactory;
38
39 /***
40 * A helper class for connection managers to track idle connections.
41 *
42 * <p>This class is not synchronized.</p>
43 *
44 * @see org.apache.commons.httpclient.HttpConnectionManager#closeIdleConnections(long)
45 *
46 * @since 3.0
47 */
48 public class IdleConnectionHandler {
49
50 private static final Log LOG = LogFactory.getLog(IdleConnectionHandler.class);
51
52 /*** Holds connections and the time they were added. */
53 private Map connectionToAdded = new HashMap();
54
55 /***
56 *
57 */
58 public IdleConnectionHandler() {
59 super();
60 }
61
62 /***
63 * Registers the given connection with this handler. The connection will be held until
64 * {@link #remove(HttpConnection)} or {@link #closeIdleConnections(long)} is called.
65 *
66 * @param connection the connection to add
67 *
68 * @see #remove(HttpConnection)
69 */
70 public void add(HttpConnection connection) {
71
72 Long timeAdded = new Long(System.currentTimeMillis());
73
74 if (LOG.isDebugEnabled()) {
75 LOG.debug("Adding connection at: " + timeAdded);
76 }
77
78 connectionToAdded.put(connection, timeAdded);
79 }
80
81 /***
82 * Removes the given connection from the list of connections to be closed when idle.
83 * @param connection
84 */
85 public void remove(HttpConnection connection) {
86 connectionToAdded.remove(connection);
87 }
88
89 /***
90 * Removes all connections referenced by this handler.
91 */
92 public void removeAll() {
93 this.connectionToAdded.clear();
94 }
95
96 /***
97 * Closes connections that have been idle for at least the given amount of time.
98 *
99 * @param idleTime the minimum idle time, in milliseconds, for connections to be closed
100 */
101 public void closeIdleConnections(long idleTime) {
102
103
104 long idleTimeout = System.currentTimeMillis() - idleTime;
105
106 if (LOG.isDebugEnabled()) {
107 LOG.debug("Checking for connections, idleTimeout: " + idleTimeout);
108 }
109
110 Iterator connectionIter = connectionToAdded.keySet().iterator();
111
112 while (connectionIter.hasNext()) {
113 HttpConnection conn = (HttpConnection) connectionIter.next();
114 Long connectionTime = (Long) connectionToAdded.get(conn);
115 if (connectionTime.longValue() <= idleTimeout) {
116 if (LOG.isDebugEnabled()) {
117 LOG.debug("Closing connection, connection time: " + connectionTime);
118 }
119 connectionIter.remove();
120 conn.close();
121 }
122 }
123 }
124 }