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 package org.apache.http.impl.client;
29
30 import java.util.concurrent.ThreadFactory;
31 import java.util.concurrent.TimeUnit;
32
33 import org.apache.http.conn.HttpClientConnectionManager;
34 import org.apache.http.util.Args;
35
36
37
38
39
40
41
42 public final class IdleConnectionEvictor {
43
44 private final HttpClientConnectionManager connectionManager;
45 private final ThreadFactory threadFactory;
46 private final Thread thread;
47 private final long sleepTimeMs;
48 private final long maxIdleTimeMs;
49
50 private volatile Exception exception;
51
52 public IdleConnectionEvictor(
53 final HttpClientConnectionManager connectionManager,
54 final ThreadFactory threadFactory,
55 final long sleepTime, final TimeUnit sleepTimeUnit,
56 final long maxIdleTime, final TimeUnit maxIdleTimeUnit) {
57 this.connectionManager = Args.notNull(connectionManager, "Connection manager");
58 this.threadFactory = threadFactory != null ? threadFactory : new DefaultThreadFactory();
59 this.sleepTimeMs = sleepTimeUnit != null ? sleepTimeUnit.toMillis(sleepTime) : sleepTime;
60 this.maxIdleTimeMs = maxIdleTimeUnit != null ? maxIdleTimeUnit.toMillis(maxIdleTime) : maxIdleTime;
61 this.thread = this.threadFactory.newThread(new Runnable() {
62 @Override
63 public void run() {
64 try {
65 while (!Thread.currentThread().isInterrupted()) {
66 Thread.sleep(sleepTimeMs);
67 connectionManager.closeExpiredConnections();
68 if (maxIdleTimeMs > 0) {
69 connectionManager.closeIdleConnections(maxIdleTimeMs, TimeUnit.MILLISECONDS);
70 }
71 }
72 } catch (final Exception ex) {
73 exception = ex;
74 }
75
76 }
77 });
78 }
79
80 public IdleConnectionEvictor(
81 final HttpClientConnectionManager connectionManager,
82 final long sleepTime, final TimeUnit sleepTimeUnit,
83 final long maxIdleTime, final TimeUnit maxIdleTimeUnit) {
84 this(connectionManager, null, sleepTime, sleepTimeUnit, maxIdleTime, maxIdleTimeUnit);
85 }
86
87 public IdleConnectionEvictor(
88 final HttpClientConnectionManager connectionManager,
89 final long maxIdleTime, final TimeUnit maxIdleTimeUnit) {
90 this(connectionManager, null,
91 maxIdleTime > 0 ? maxIdleTime : 5, maxIdleTimeUnit != null ? maxIdleTimeUnit : TimeUnit.SECONDS,
92 maxIdleTime, maxIdleTimeUnit);
93 }
94
95 public void start() {
96 thread.start();
97 }
98
99 public void shutdown() {
100 thread.interrupt();
101 }
102
103 public boolean isRunning() {
104 return thread.isAlive();
105 }
106
107 public void awaitTermination(final long time, final TimeUnit timeUnit) throws InterruptedException {
108 thread.join((timeUnit != null ? timeUnit : TimeUnit.MILLISECONDS).toMillis(time));
109 }
110
111 static class DefaultThreadFactory implements ThreadFactory {
112
113 @Override
114 public Thread newThread(final Runnable r) {
115 final Thread t = new Thread(r, "Connection evictor");
116 t.setDaemon(true);
117 return t;
118 }
119
120 }
121
122
123 }