Skip to content

Instantly share code, notes, and snippets.

@HubertWo
Last active February 14, 2017 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HubertWo/ad16547fecaca76e14a0016a74f19c33 to your computer and use it in GitHub Desktop.
Save HubertWo/ad16547fecaca76e14a0016a74f19c33 to your computer and use it in GitHub Desktop.
Short example how to avoid problem with infinite amount of ConnectionPools created by OkHttpClient 3.6.0.
package com.github.hubertwo.okhttptest;
import okhttp3.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* This is a short example how to avoid problem
* with infinite amount of ConnectionPools created by OkHttpClient 3.6.0.
*/
public class App {
public static void main(String[] args) throws IOException, InterruptedException {
// Create you own ConnectionPool and use it whenever
// you are creating OkHttpClient.
final ConnectionPool connectionPool = new ConnectionPool(2, 10, TimeUnit.SECONDS);
for (int i = 0; i < 10; i++) {
// Create new client with previously created connection pool.
OkHttpClient client = new OkHttpClient.Builder()
.connectionPool(connectionPool) // If you want to reproduce problem comment this line.
.build();
// Executing request.
Request request = new Request.Builder()
.url("https://github.com/HubertWo")
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response.code());
}
// Close OkHttpClient according to:
// https://square.github.io/okhttp/3.x/okhttp/okhttp3/OkHttpClient.html
client.dispatcher().executorService().shutdown();
client.connectionPool().evictAll();
// For better visualization.
TimeUnit.SECONDS.sleep(2);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>OkHttpTest</groupId>
<artifactId>OkHttpTest</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
</dependencies>
</project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment