Example usage for java.util.concurrent Executors newCachedThreadPool

List of usage examples for java.util.concurrent Executors newCachedThreadPool

Introduction

In this page you can find the example usage for java.util.concurrent Executors newCachedThreadPool.

Prototype

public static ExecutorService newCachedThreadPool() 

Source Link

Document

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.

Usage

From source file:com.mgmtp.perfload.core.console.LtConsole.java

public static void main(final String[] args) {
    JCommander jCmd = null;//from  ww w.j a  v  a2s . c  o m
    try {
        LtConsoleArgs cliArgs = new LtConsoleArgs();
        jCmd = new JCommander(cliArgs);
        jCmd.parse(args);

        LOG.info("Starting perfLoad Console...");
        LOG.info(cliArgs.toString());

        int daemonCount = cliArgs.daemons.size();
        List<Daemon> daemons = newArrayListWithCapacity(daemonCount);
        for (int i = 0; i < daemonCount; i++) {
            // daemon id is 1-based
            int daemonId = i + 1;
            daemons.add(Daemon.fromHostAndPort(daemonId, cliArgs.daemons.get(i)));
        }
        daemons = ImmutableList.copyOf(daemons);

        XmlConfigReader configReader = new XmlConfigReader(new File("."), cliArgs.testplan);
        TestplanConfig config = configReader.readConfig();
        int totalThreadCount = config.getTotalThreadCount();
        StatusTransformer transformer = new FileStatusTransformer(totalThreadCount, new File("ltStatus.txt"),
                new File("ltThreads.txt"), "UTF-8");

        LtMetaInfoHandler metaInfoHandler = new LtMetaInfoHandler();
        LtConsole console = new LtConsole(config, Executors.newCachedThreadPool(), transformer, metaInfoHandler,
                daemons, cliArgs.shutdownDaemons, cliArgs.abort, TimeUnit.MINUTES.toMillis(cliArgs.timeout));
        console.execute();
    } catch (ParameterException ex) {
        jCmd.usage();
        System.exit(1);
    } catch (Exception ex) {
        LOG.error(ex.getMessage(), ex);
        System.exit(-1);
    }
}

From source file:com.hengtong.library.async.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from w  w  w  .  jav a2s.c  o m
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, timeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = Executors.newCachedThreadPool();
    requestMap = new WeakHashMap<Context, List<RequestHandle>>();
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:com.zch.safelottery.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*  w ww.j  a v  a2 s . c  o  m*/
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, timeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, "android-async-http/1.4.5");

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = Executors.newCachedThreadPool();
    requestMap = new WeakHashMap<Context, List<RequestHandle>>();
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:com.example.wechatsample.library.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from   ww  w. j a  va  2  s  .  c o  m*/
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));
    ThreadSafeClientConnManager cm = null;
    try {
        //  https?
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // ??

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", sf, 443));
        schemeRegistry.register(new Scheme("https", sf, 8443));
        cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();
}

From source file:lynxtools.async_download.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//  www .  j a  va  2  s  .  c o m
 */
public AsyncHttpClient() {
    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, socketTimeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, socketTimeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    if (AsyncWraper.getTrustAllCertificates()) {
        try {
            //accepting all certificates because fuck this.
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            schemeRegistry.register(new Scheme("https", sf, 443));
            System.out.println("accepting all certificates");
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    }

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(response.getEntity()));
                        break;
                    }
                }
            }
        }
    });

    httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES));

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();

    clientHeaderMap = new HashMap<String, String>();

}

From source file:com.jagornet.dhcpv6.client.TestClient.java

/**
 * Start sending DHCPv6 INFORM_REQUESTs.
 *//*from  ww w  . ja  v  a  2  s.  c o  m*/
public void start() {
    DatagramChannelFactory factory = null;
    if (mcastNetIf != null) {
        factory = new OioDatagramChannelFactory(Executors.newCachedThreadPool());
        serverAddr = DhcpConstants.ALL_DHCP_RELAY_AGENTS_AND_SERVERS;
    } else {
        factory = new NioDatagramChannelFactory(Executors.newCachedThreadPool());
    }

    InetSocketAddress server = new InetSocketAddress(serverAddr, serverPort);
    InetSocketAddress client = new InetSocketAddress(clientPort);

    ChannelPipeline pipeline = Channels.pipeline();
    pipeline.addLast("logger", new LoggingHandler());
    pipeline.addLast("encoder", new DhcpChannelEncoder());
    pipeline.addLast("decoder", new DhcpChannelDecoder(client));
    pipeline.addLast("handler", this);

    if (mcastNetIf != null) {
        channel = factory.newChannel(pipeline);
        channel.getConfig().setNetworkInterface(mcastNetIf);
    } else {
        channel = factory.newChannel(pipeline);
    }
    channel.bind(client);

    List<DhcpMessage> requestMsgs = buildRequestMessages();

    for (DhcpMessage msg : requestMsgs) {
        executor.execute(new RequestSender(msg, server));
    }

    long ms = 0;
    if (rapidCommit)
        ms = requestMsgs.size() * 200;
    else
        ms = requestMsgs.size() * 20;

    synchronized (requestMap) {
        try {
            log.info("Waiting total of " + ms + " milliseconds for completion");
            requestMap.wait(ms);
        } catch (InterruptedException ex) {
            log.error("Interrupted", ex);
        }
    }

    log.info("Successfully processed " + successCnt + " of " + requestsSent + " messages in "
            + (endTime - startTime) + " milliseconds");

    log.info("Shutting down executor...");
    executor.shutdownNow();
    log.info("Closing channel...");
    channel.close();
    log.info("Done.");
    System.exit(0);
}

From source file:com.zch.safelottery.http.AsyncHttpClientForDownload.java

/**
 * Creates a new AsyncHttpClient.// w ww . java2s  . c  o m
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClientForDownload(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, timeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams, "android-async-http/1.4.5");

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = Executors.newCachedThreadPool();
    requestMap = new WeakHashMap<Context, List<RequestHandle>>();
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:cn.edu.zzu.wemall.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient.//from w  w w  .jav  a 2  s . com
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, timeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:com.google.firebase.auth.migration.AuthMigrator.java

private Task<String> exchangeToken(final String legacyToken) {
    if (legacyToken == null) {
        return Tasks.forResult(null);
    }//from   www .j  av  a  2s  .  com
    return Tasks.call(Executors.newCachedThreadPool(), new Callable<String>() {
        @Override
        public String call() throws Exception {
            JSONObject postBody = new JSONObject();
            postBody.put("token", legacyToken);
            HttpURLConnection connection = (HttpURLConnection) exchangeEndpoint.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestMethod("POST");
            OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
            try {
                osw.write(postBody.toString());
                osw.flush();
            } finally {
                osw.close();
            }
            int responseCode = connection.getResponseCode();

            InputStream is;
            if (responseCode >= 400) {
                is = connection.getErrorStream();
            } else {
                is = connection.getInputStream();
            }
            try {
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int numRead = 0;
                while ((numRead = is.read(buffer)) >= 0) {
                    baos.write(buffer, 0, numRead);
                }
                JSONObject resultObject = new JSONObject(new String(baos.toByteArray()));
                if (responseCode != 200) {
                    throw new FirebaseWebRequestException(
                            resultObject.getJSONObject("error").getString("message"), responseCode);
                }
                return resultObject.getString("token");
            } finally {
                is.close();
            }
        }
    });
}

From source file:com.aoeng.degu.utils.net.asyncthhpclient.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*from  w  w  w  .j av  a 2s.  c om*/
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, timeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(httpParams,
            String.format("android-async-http/%s (http://loopj.com/android-async-http)", VERSION));

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = Executors.newCachedThreadPool();
    requestMap = new WeakHashMap<Context, List<WeakReference<Future<?>>>>();
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}