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