Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public final class HttpClientPool {
- private static HttpClientPool instance = null;
- private PoolingHttpClientConnectionManager manager;
- private IdleConnectionMonitorThread monitorThread;
- private final CloseableHttpClient client;
- public static HttpClientPool getInstance() {
- if (instance == null) {
- synchronized(HttpClientPool.class) {
- if (instance == null) {
- instance = new HttpClientPool();
- }
- }
- }
- return instance;
- }
- private HttpClientPool() {
- manager = new PoolingHttpClientConnectionManager();
- client = HttpClients.custom().setConnectionManager(manager).build();
- monitorThread = new IdleConnectionMonitorThread(manager);
- monitorThread.setDaemon(true);
- monitorThread.start();
- }
- public CloseableHttpClient getClient() {
- return client;
- }
- }
- class IdleConnectionMonitorThread extends Thread {
- private final HttpClientConnectionManager connMgr;
- private volatile boolean shutdown;
- IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
- super();
- this.connMgr = connMgr;
- }
- @Override
- public void run() {
- try {
- while (!shutdown) {
- synchronized(this) {
- wait(5000);
- // Close expired connections
- connMgr.closeExpiredConnections();
- // Optionally, close connections
- // that have been idle longer than 30 sec
- connMgr.closeIdleConnections(60, TimeUnit.SECONDS);
- }
- }
- } catch (InterruptedException ex) {
- //
- }
- }
- void shutdown() {
- shutdown = true;
- synchronized(this) {
- notifyAll();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement