88import java .io .IOException ;
99import java .net .InetSocketAddress ;
1010import java .net .Proxy ;
11+ import java .util .concurrent .TimeUnit ;
1112import okhttp3 .CertificatePinner ;
13+ import okhttp3 .ConnectionPool ;
1214import okhttp3 .OkHttpClient ;
1315import retrofit2 .Call ;
1416import retrofit2 .Response ;
@@ -21,6 +23,19 @@ public class DuoConnector {
2123
2224 private static final int SUCCESS_STATUS_CODE = 200 ;
2325
26+ /**
27+ * Maximum number of idle connections to keep in the pool.
28+ * 5 is the OkHttp default, and reasonable for our needs.
29+ */
30+ private static final int MAX_IDLE_CONNECTIONS = 5 ;
31+
32+ /**
33+ * How long to keep idle connections alive before closing them. The Duo service closes
34+ * connections server-side after 1 minute, so we close them slightly earlier to avoid
35+ * holding on to a stale connection.
36+ */
37+ private static final int CONNECTION_KEEP_ALIVE_SECONDS = 55 ;
38+
2439 /**
2540 * DuoConnector Constructor.
2641 *
@@ -47,16 +62,20 @@ public DuoConnector(String apiHost, String proxyHost, Integer proxyPort, String[
4762 throws DuoException {
4863 CertificatePinner duoCertificatePinner = new CertificatePinner .Builder ()
4964 .add (apiHost , caCerts ).build ();
65+ ConnectionPool connectionPool = new ConnectionPool (
66+ MAX_IDLE_CONNECTIONS , CONNECTION_KEEP_ALIVE_SECONDS , TimeUnit .SECONDS );
5067 OkHttpClient client ;
5168 if (proxyHost != null && proxyPort != null ) {
5269 Proxy proxy = new Proxy (Proxy .Type .HTTP , new InetSocketAddress (proxyHost , proxyPort ));
5370 client = new OkHttpClient .Builder ()
5471 .certificatePinner (duoCertificatePinner )
72+ .connectionPool (connectionPool )
5573 .proxy (proxy )
5674 .build ();
5775 } else {
5876 client = new OkHttpClient .Builder ()
5977 .certificatePinner (duoCertificatePinner )
78+ .connectionPool (connectionPool )
6079 .build ();
6180 }
6281
0 commit comments