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.integration;
29
30 import java.net.URI;
31 import java.util.concurrent.TimeUnit;
32
33 import org.apache.http.HttpHost;
34 import org.apache.http.client.ClientProtocolException;
35 import org.apache.http.client.methods.CloseableHttpResponse;
36 import org.apache.http.client.methods.HttpGet;
37 import org.apache.http.impl.client.CloseableHttpClient;
38 import org.apache.http.impl.client.IdleConnectionEvictor;
39 import org.apache.http.localserver.LocalServerTestBase;
40 import org.apache.http.util.EntityUtils;
41 import org.junit.Test;
42
43 public class TestIdleConnectionEviction extends LocalServerTestBase {
44
45 @Test
46 public void testIdleConnectionEviction() throws Exception {
47 this.connManager.setDefaultMaxPerRoute(10);
48 this.connManager.setMaxTotal(50);
49
50 final HttpHost target = start();
51
52 final IdleConnectionEvictor idleConnectionMonitor = new IdleConnectionEvictor(
53 this.connManager, 50, TimeUnit.MILLISECONDS);
54 idleConnectionMonitor.start();
55
56 final URI requestUri = new URI("/random/1024");
57 final WorkerThread[] workers = new WorkerThread[5];
58 for (int i = 0; i < workers.length; i++) {
59 workers[i] = new WorkerThread(httpclient, target, requestUri, 200);
60 }
61 for (final WorkerThread worker : workers) {
62 worker.start();
63 }
64 for (final WorkerThread worker : workers) {
65 worker.join();
66 final Exception ex = worker.getException();
67 if (ex != null) {
68 throw ex;
69 }
70 }
71 idleConnectionMonitor.shutdown();
72 }
73
74 static class WorkerThread extends Thread {
75
76 private final CloseableHttpClient httpclient;
77 private final HttpHost target;
78 private final URI requestUri;
79 private final int count;
80
81 private volatile Exception ex;
82
83 public WorkerThread(
84 final CloseableHttpClient httpclient,
85 final HttpHost target,
86 final URI requestUri,
87 final int count) {
88 super();
89 this.httpclient = httpclient;
90 this.target = target;
91 this.requestUri = requestUri;
92 this.count = count;
93 }
94
95 @Override
96 public void run() {
97 try {
98 for (int i = 0; i < this.count; i++) {
99 final HttpGet httpget = new HttpGet(this.requestUri);
100 final CloseableHttpResponse response = this.httpclient.execute(this.target, httpget);
101 try {
102 final int status = response.getStatusLine().getStatusCode();
103 if (status != 200) {
104 throw new ClientProtocolException("Unexpected status code: " + status);
105 }
106 EntityUtils.consume(response.getEntity());
107 Thread.sleep(10);
108 } finally {
109 response.close();
110 }
111 }
112 } catch (final Exception ex) {
113 this.ex = ex;
114 }
115 }
116
117 public Exception getException() {
118 return ex;
119 }
120
121 }
122
123 }