Example usage for org.apache.http.pool PoolStats getAvailable

List of usage examples for org.apache.http.pool PoolStats getAvailable

Introduction

In this page you can find the example usage for org.apache.http.pool PoolStats getAvailable.

Prototype

public int getAvailable() 

Source Link

Usage

From source file:interoperabilite.webservice.client.ClientEvictExpiredConnections.java

public static void main(String[] args) throws Exception {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(100);/*  w  w  w.  ja  va  2 s. c o  m*/
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).evictExpiredConnections()
            .evictIdleConnections(5L, TimeUnit.SECONDS).build();
    try {
        // create an array of URIs to perform GETs on
        String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/",
                "http://hc.apache.org/httpcomponents-client-ga/", };

        for (int i = 0; i < urisToGet.length; i++) {
            String requestURI = urisToGet[i];
            HttpGet request = new HttpGet(requestURI);

            System.out.println("Executing request " + requestURI);

            CloseableHttpResponse response = httpclient.execute(request);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        }

        PoolStats stats1 = cm.getTotalStats();
        System.out.println("Connections kept alive: " + stats1.getAvailable());

        // Sleep 10 sec and let the connection evictor do its job
        Thread.sleep(10000);

        PoolStats stats2 = cm.getTotalStats();
        System.out.println("Connections kept alive: " + stats2.getAvailable());

    } finally {
        httpclient.close();
    }
}

From source file:com.yahoo.sql4d.sql4ddriver.DruidNodeAccessor.java

public static Map<String, Integer> getConnectionPoolStats() {
    Map<String, Integer> stats = new HashMap<>();
    PoolStats poolStats = pool.getTotalStats();
    stats.put("availableConnections", poolStats.getAvailable());
    stats.put("maxConnections", poolStats.getMax());
    stats.put("leasedConnections", poolStats.getLeased());
    stats.put("pendingConnections", poolStats.getPending());
    stats.put("defaultMaxPerRoute", pool.getDefaultMaxPerRoute());
    return stats;
}

From source file:com.joyent.manta.http.PoolStatsMBean.java

/**
 * Utility method that pulls an attribute's value from the statistics object.
 * @param attribute attribute to pull/*w w w . j a  v  a2  s.c  om*/
 * @param stats status object to query
 * @return result as integer or null if no mapping exists
 */
private static Integer getAttributeFromPoolStats(final String attribute, final PoolStats stats) {
    switch (attribute) {
    case "leased":
        return stats.getLeased();
    case "pending":
        return stats.getPending();
    case "available":
        return stats.getAvailable();
    case "max":
        return stats.getMax();
    default:
        return null;
    }
}

From source file:PerformanceQueues_p.java

public static serverObjects respond(final RequestHeader header, final serverObjects post,
        final serverSwitch env) {
    // return variable that accumulates replacements
    final Switchboard sb = (Switchboard) env;
    final serverObjects prop = new serverObjects();
    File defaultSettingsFile = new File(sb.getAppPath(), "defaults/yacy.init");

    /* Acquire a transaction token for the next POST form submission */
    prop.put(TransactionManager.TRANSACTION_TOKEN_PARAM, TransactionManager.getTransactionToken(header));

    // get segment
    Segment indexSegment = sb.index;

    if (post != null) {
        /* Check the transaction is valid : validation apply then for every uses of this post parameter */
        TransactionManager.checkPostTransaction(header, post);

        if (post.containsKey("resetObserver")) {
            /* The the reset state button is pushed, we only perform this action and do not save other form field values at the same time */
            MemoryControl.resetProperState();
        } else {//from   ww  w .  j  a v  a2 s.  c o  m
            if (post.containsKey("defaultFile")) {
                // TODO check file-path!
                final File value = new File(sb.getAppPath(), post.get("defaultFile", "defaults/yacy.init"));
                // check if value is readable file
                if (value.exists() && value.isFile() && value.canRead()) {
                    defaultSettingsFile = value;
                }
            }
            if (post.containsKey("Xmx")) {
                int xmx = post.getInt("Xmx", 600); // default maximum heap size
                if (OS.isWin32)
                    xmx = Math.min(2000, xmx);
                int xms = xmx; //Math.min(xmx, Math.max(90, xmx / 10));
                sb.setConfig("javastart_Xmx", "Xmx" + xmx + "m");
                sb.setConfig("javastart_Xms", "Xms" + xms + "m");
                prop.put("setStartupCommit", "1");

                /* Acquire a transaction token for the restart operation */
                prop.put("setStartupCommit_" + TransactionManager.TRANSACTION_TOKEN_PARAM,
                        TransactionManager.getTransactionToken(header, "/Steering.html"));
            }
            if (post.containsKey("diskFree")) {
                sb.setConfig(SwitchboardConstants.RESOURCE_DISK_FREE_MIN_STEADYSTATE, post.getLong("diskFree",
                        SwitchboardConstants.RESOURCE_DISK_FREE_MIN_STEADYSTATE_DEFAULT));
            }
            if (post.containsKey("diskFreeHardlimit")) {
                sb.setConfig(SwitchboardConstants.RESOURCE_DISK_FREE_MIN_UNDERSHOT, post.getLong(
                        "diskFreeHardlimit", SwitchboardConstants.RESOURCE_DISK_FREE_MIN_UNDERSHOT_DEFAULT));

                /* This is a checkbox in Performance_p.html : when not checked the value is not in post parameters, 
                 * so we take only in account when the relate diskFreeHardlimit is set */
                sb.setConfig(SwitchboardConstants.RESOURCE_DISK_FREE_AUTOREGULATE,
                        post.getBoolean("diskFreeAutoregulate"));
            }
            if (post.containsKey("diskUsed")) {
                sb.setConfig(SwitchboardConstants.RESOURCE_DISK_USED_MAX_STEADYSTATE, post.getLong("diskUsed",
                        SwitchboardConstants.RESOURCE_DISK_USED_MAX_STEADYSTATE_DEFAULT));
            }
            if (post.containsKey("diskUsedHardlimit")) {
                sb.setConfig(SwitchboardConstants.RESOURCE_DISK_USED_MAX_OVERSHOT, post.getLong(
                        "diskUsedHardlimit", SwitchboardConstants.RESOURCE_DISK_USED_MAX_OVERSHOT_DEFAULT));

                /* This is a checkbox in Performance_p.html : when not checked the value is not in post parameters, 
                 * so we take only in account when the related diskFreeHardlimit is set */
                sb.setConfig(SwitchboardConstants.RESOURCE_DISK_USED_AUTOREGULATE,
                        post.getBoolean("diskUsedAutoregulate"));
            }
            if (post.containsKey("memoryAcceptDHT")) {
                sb.setConfig(SwitchboardConstants.MEMORY_ACCEPTDHT, post.getInt("memoryAcceptDHT", 50));
            }
        }
    }
    final Map<String, String> defaultSettings = ((post == null) || (!(post.containsKey("submitdefault"))))
            ? null
            : FileUtils.loadMap(defaultSettingsFile);
    Iterator<String> threads = sb.threadNames();
    String threadName;
    BusyThread thread;

    final boolean xml = header.getPathInfo().endsWith(".xml");
    prop.setLocalized(!xml);

    // calculate totals
    long blocktime_total = 0, sleeptime_total = 0, exectime_total = 0;
    while (threads.hasNext()) {
        threadName = threads.next();
        thread = sb.getThread(threadName);
        blocktime_total += thread.getBlockTime();
        sleeptime_total += thread.getSleepTime();
        exectime_total += thread.getExecTime();
    }
    if (blocktime_total == 0)
        blocktime_total = 1;
    if (sleeptime_total == 0)
        sleeptime_total = 1;
    if (exectime_total == 0)
        exectime_total = 1;

    // set templates for latest news from the threads
    long blocktime, sleeptime, exectime;
    long idlesleep, busysleep, memuse, memprereq;
    double loadprereq;
    int queuesize;
    threads = sb.threadNames();
    int c = 0;
    long idleCycles, busyCycles, memshortageCycles, highCPUCycles;
    // set profile?
    final boolean setProfile = (post != null && post.containsKey("submitdefault"));
    final boolean setDelay = (post != null) && (post.containsKey("submitdelay"));
    // save used settings file to config
    if (setProfile && post != null) {
        sb.setConfig("performanceSpeed", post.getInt("profileSpeed", 100));
    }

    IndexCell<WordReference> rwi = indexSegment.termIndex();
    while (threads.hasNext()) {
        threadName = threads.next();
        thread = sb.getThread(threadName);

        // set values to templates
        prop.put("table_" + c + "_threadname", threadName);

        prop.putHTML("table_" + c + "_hasurl_shortdescr", thread.getShortDescription());
        if (thread.getMonitorURL() == null) {
            prop.put("table_" + c + "_hasurl", "0");
        } else {
            prop.put("table_" + c + "_hasurl", "1");
            prop.put("table_" + c + "_hasurl_url", thread.getMonitorURL());
        }
        prop.putHTML("table_" + c + "_longdescr", thread.getLongDescription());
        queuesize = thread.getJobCount();
        prop.put("table_" + c + "_queuesize",
                (queuesize == Integer.MAX_VALUE) ? "unlimited" : Formatter.number(queuesize, !xml));

        blocktime = thread.getBlockTime();
        sleeptime = thread.getSleepTime();
        exectime = thread.getExecTime();
        memuse = thread.getMemoryUse();
        idleCycles = thread.getIdleCycles();
        busyCycles = thread.getBusyCycles();
        memshortageCycles = thread.getOutOfMemoryCycles();
        highCPUCycles = thread.getHighCPUCycles();
        prop.putNum("table_" + c + "_blocktime", blocktime / 1000);
        prop.putNum("table_" + c + "_blockpercent", 100 * blocktime / blocktime_total);
        prop.putNum("table_" + c + "_sleeptime", sleeptime / 1000);
        prop.putNum("table_" + c + "_sleeppercent", 100 * sleeptime / sleeptime_total);
        prop.putNum("table_" + c + "_exectime", exectime / 1000);
        prop.putNum("table_" + c + "_execpercent", 100 * exectime / exectime_total);
        prop.putNum("table_" + c + "_totalcycles", idleCycles + busyCycles + memshortageCycles + highCPUCycles);
        prop.putNum("table_" + c + "_idlecycles", idleCycles);
        prop.putNum("table_" + c + "_busycycles", busyCycles);
        prop.putNum("table_" + c + "_memscycles", memshortageCycles);
        prop.putNum("table_" + c + "_highcpucycles", highCPUCycles);
        prop.putNum("table_" + c + "_sleeppercycle",
                ((idleCycles + busyCycles) == 0) ? -1 : sleeptime / (idleCycles + busyCycles));
        prop.putNum("table_" + c + "_execpercycle", (busyCycles == 0) ? -1 : exectime / busyCycles);
        prop.putNum("table_" + c + "_memusepercycle", (busyCycles == 0) ? -1 : memuse / busyCycles / 1024);

        // load with old values
        idlesleep = sb.getConfigLong(threadName + "_idlesleep", 1000);
        busysleep = sb.getConfigLong(threadName + "_busysleep", 100);
        memprereq = sb.getConfigLong(threadName + "_memprereq", 0);
        loadprereq = sb.getConfigFloat(threadName + "_loadprereq", 9);
        if (setDelay && post != null) {
            // load with new values
            idlesleep = post.getLong(threadName + "_idlesleep", idlesleep);
            busysleep = post.getLong(threadName + "_busysleep", busysleep);
            memprereq = post.getLong(threadName + "_memprereq", memprereq) * 1024l;
            if (memprereq == 0)
                memprereq = sb.getConfigLong(threadName + "_memprereq", 0);
            loadprereq = post.getDouble(threadName + "_loadprereq", loadprereq);
            if (loadprereq == 0)
                loadprereq = sb.getConfigFloat(threadName + "_loadprereq", 9);

            // check values to prevent short-cut loops
            if (idlesleep < 1000)
                idlesleep = 1000;

            sb.setThreadPerformance(threadName, idlesleep, busysleep, memprereq, loadprereq);
            idlesleep = sb.getConfigLong(threadName + "_idlesleep", idlesleep);
            busysleep = sb.getConfigLong(threadName + "_busysleep", busysleep);
        }
        if (setProfile) {
            // load with new values
            idlesleep = Long
                    .parseLong(d(defaultSettings.get(threadName + "_idlesleep"), String.valueOf(idlesleep)));
            busysleep = Long
                    .parseLong(d(defaultSettings.get(threadName + "_busysleep"), String.valueOf(busysleep)));
            memprereq = Long
                    .parseLong(d(defaultSettings.get(threadName + "_memprereq"), String.valueOf(memprereq)));
            loadprereq = Double.parseDouble(
                    d(defaultSettings.get(threadName + "_loadprereq"), String.valueOf(loadprereq)));
            // check values to prevent short-cut loops
            if (idlesleep < 1000)
                idlesleep = 1000;
            //if (threadName.equals(plasmaSwitchboardConstants.CRAWLJOB_LOCAL_CRAWL) && (busysleep < 50)) busysleep = 50;
            sb.setThreadPerformance(threadName, idlesleep, busysleep, memprereq, loadprereq);
        }
        prop.put("table_" + c + "_idlesleep", idlesleep);
        prop.put("table_" + c + "_busysleep", busysleep);
        prop.put("table_" + c + "_memprereq", memprereq / 1024);
        prop.put("table_" + c + "_loadprereq", loadprereq);
        // disallow setting of memprereq for indexer to prevent db from throwing OOMs
        // prop.put("table_" + c + "_disabled", /*(threadName.endsWith("_indexing")) ? 1 :*/ "0");
        prop.put("table_" + c + "_recommendation", threadName.endsWith("_indexing") ? "1" : "0");
        prop.putNum("table_" + c + "_recommendation_value",
                rwi == null ? 0 : threadName.endsWith("_indexing") ? (rwi.minMem() / 1024) : 0);
        c++;
    }
    prop.put("table", c);

    c = 0;
    final int[] speedValues = { 200, 150, 100, 50, 25, 10 };
    final int usedspeed = sb.getConfigInt("performanceSpeed", 100);
    for (final int speed : speedValues) {
        prop.put("speed_" + c + "_value", speed);
        prop.put("speed_" + c + "_label", speed + " %");
        prop.put("speed_" + c + "_used", (speed == usedspeed) ? "1" : "0");
        c++;
    }
    prop.put("speed", c);

    if ((post != null) && (post.containsKey("cacheSizeSubmit"))) {
        final int wordCacheMaxCount = post.getInt("wordCacheMaxCount", 20000);
        sb.setConfig(SwitchboardConstants.WORDCACHE_MAX_COUNT, Integer.toString(wordCacheMaxCount));
        if (rwi != null)
            rwi.setBufferMaxWordCount(wordCacheMaxCount);
    }

    /* Setting remote searches max loads */
    if (post != null) {
        if (post.containsKey("setRemoteSearchLoads")) {
            float loadValue = post.getFloat("remoteSearchRWIMaxLoad",
                    sb.getConfigFloat(SwitchboardConstants.REMOTESEARCH_MAXLOAD_RWI,
                            SwitchboardConstants.REMOTESEARCH_MAXLOAD_RWI_DEFAULT));
            sb.setConfig(SwitchboardConstants.REMOTESEARCH_MAXLOAD_RWI, loadValue);

            loadValue = post.getFloat("remoteSearchSolrMaxLoad",
                    sb.getConfigFloat(SwitchboardConstants.REMOTESEARCH_MAXLOAD_SOLR,
                            SwitchboardConstants.REMOTESEARCH_MAXLOAD_SOLR_DEFAULT));
            sb.setConfig(SwitchboardConstants.REMOTESEARCH_MAXLOAD_SOLR, loadValue);
        } else if (post.containsKey("defaultRemoteSearchLoads")) {
            sb.setConfig(SwitchboardConstants.REMOTESEARCH_MAXLOAD_RWI,
                    SwitchboardConstants.REMOTESEARCH_MAXLOAD_RWI_DEFAULT);
            sb.setConfig(SwitchboardConstants.REMOTESEARCH_MAXLOAD_SOLR,
                    SwitchboardConstants.REMOTESEARCH_MAXLOAD_SOLR_DEFAULT);
        }
    }

    if ((post != null) && (post.containsKey("poolConfig"))) {

        /*
         * configuring the crawler pool
         */
        // get the current crawler pool configuration
        int maxBusy = post.getInt("Crawler Pool_maxActive", 8);

        // storing the new values into configfile
        sb.setConfig(SwitchboardConstants.CRAWLER_THREADS_ACTIVE_MAX, maxBusy);

        /*
         * configuring the robots.txt loading pool
         */
        // get the current crawler pool configuration
        maxBusy = post.getInt("Robots.txt Pool_maxActive",
                SwitchboardConstants.ROBOTS_TXT_THREADS_ACTIVE_MAX_DEFAULT);

        // storing the new values into configfile
        sb.setConfig(SwitchboardConstants.ROBOTS_TXT_THREADS_ACTIVE_MAX, maxBusy);

        /*
         * configuring the http pool
         */
        try {
            maxBusy = post.getInt("httpd Session Pool_maxActive", 8);
        } catch (final NumberFormatException e) {
            maxBusy = 8;
        }

        ConnectionInfo.setServerMaxcount(maxBusy);

        // storing the new values into configfile
        sb.setConfig("httpdMaxBusySessions", maxBusy);

    }

    if ((post != null) && (post.containsKey("connectionPoolConfig"))) {

        /* Configure the general outgoing HTTP connection pool */
        int maxTotal = post.getInt(SwitchboardConstants.HTTP_OUTGOING_POOL_GENERAL_MAX_TOTAL,
                SwitchboardConstants.HTTP_OUTGOING_POOL_GENERAL_MAX_TOTAL_DEFAULT);
        if (maxTotal > 0) {
            sb.setConfig(SwitchboardConstants.HTTP_OUTGOING_POOL_GENERAL_MAX_TOTAL, maxTotal);
            HTTPClient.initPoolMaxConnections(HTTPClient.CONNECTION_MANAGER, maxTotal);
        }

        /* Configure the remote Solr outgoing HTTP connection pool */
        maxTotal = post.getInt(SwitchboardConstants.HTTP_OUTGOING_POOL_REMOTE_SOLR_MAX_TOTAL,
                SwitchboardConstants.HTTP_OUTGOING_POOL_REMOTE_SOLR_MAX_TOTAL_DEFAULT);
        if (maxTotal > 0) {
            sb.setConfig(SwitchboardConstants.HTTP_OUTGOING_POOL_REMOTE_SOLR_MAX_TOTAL, maxTotal);
            RemoteInstance.initPoolMaxConnections(RemoteInstance.CONNECTION_MANAGER, maxTotal);
        }
    }

    if ((post != null) && (post.containsKey("onlineCautionSubmit"))) {
        sb.setConfig(SwitchboardConstants.PROXY_ONLINE_CAUTION_DELAY,
                Integer.toString(post.getInt("crawlPauseProxy", 30000)));
        sb.setConfig(SwitchboardConstants.LOCALSEACH_ONLINE_CAUTION_DELAY,
                Integer.toString(post.getInt("crawlPauseLocalsearch", 30000)));
        sb.setConfig(SwitchboardConstants.REMOTESEARCH_ONLINE_CAUTION_DELAY,
                Integer.toString(post.getInt("crawlPauseRemotesearch", 30000)));
    }

    // table cache settings
    prop.putNum("wordCacheSize", indexSegment.RWIBufferCount());
    prop.putNum("wordCacheSizeKBytes", rwi == null ? 0 : rwi.getBufferSizeBytes() / 1024L);
    prop.putNum("maxURLinCache", rwi == null ? 0 : rwi.getBufferMaxReferences());
    prop.putNum("maxAgeOfCache", rwi == null ? 0 : rwi.getBufferMaxAge() / 1000 / 60); // minutes
    prop.putNum("minAgeOfCache", rwi == null ? 0 : rwi.getBufferMinAge() / 1000 / 60); // minutes
    prop.putNum("maxWaitingWordFlush", sb.getConfigLong("maxWaitingWordFlush", 180));
    prop.put("wordCacheMaxCount", sb.getConfigLong(SwitchboardConstants.WORDCACHE_MAX_COUNT, 20000));
    prop.put("crawlPauseProxy", sb.getConfigLong(SwitchboardConstants.PROXY_ONLINE_CAUTION_DELAY, 30000));
    prop.put("crawlPauseLocalsearch",
            sb.getConfigLong(SwitchboardConstants.LOCALSEACH_ONLINE_CAUTION_DELAY, 30000));
    prop.put("crawlPauseRemotesearch",
            sb.getConfigLong(SwitchboardConstants.REMOTESEARCH_ONLINE_CAUTION_DELAY, 30000));
    prop.putNum("crawlPauseProxyCurrent", (System.currentTimeMillis() - sb.proxyLastAccess) / 1000);
    prop.putNum("crawlPauseLocalsearchCurrent", (System.currentTimeMillis() - sb.localSearchLastAccess) / 1000);
    prop.putNum("crawlPauseRemotesearchCurrent",
            (System.currentTimeMillis() - sb.remoteSearchLastAccess) / 1000);

    // table thread pool settings
    prop.put("pool_0_name", "Crawler Pool");
    prop.put("pool_0_maxActive", sb.getConfigLong(SwitchboardConstants.CRAWLER_THREADS_ACTIVE_MAX, 0));
    prop.put("pool_0_numActive", sb.crawlQueues.activeWorkerEntries().size());

    prop.put("pool_1_name", "Robots.txt Pool");
    prop.put("pool_1_maxActive", sb.getConfigInt(SwitchboardConstants.ROBOTS_TXT_THREADS_ACTIVE_MAX,
            SwitchboardConstants.ROBOTS_TXT_THREADS_ACTIVE_MAX_DEFAULT));
    prop.put("pool_1_numActive", sb.crawlQueues.activeWorkerEntries().size());

    prop.put("pool_2_name", "httpd Session Pool");
    prop.put("pool_2_maxActive", ConnectionInfo.getServerMaxcount());
    prop.put("pool_2_numActive", ConnectionInfo.getServerCount());

    prop.put("pool", "3");

    /* Connection pools settings */
    prop.put(SwitchboardConstants.HTTP_OUTGOING_POOL_GENERAL_MAX_TOTAL,
            sb.getConfigInt(SwitchboardConstants.HTTP_OUTGOING_POOL_GENERAL_MAX_TOTAL,
                    SwitchboardConstants.HTTP_OUTGOING_POOL_GENERAL_MAX_TOTAL_DEFAULT));
    prop.put(SwitchboardConstants.HTTP_OUTGOING_POOL_REMOTE_SOLR_MAX_TOTAL,
            sb.getConfigInt(SwitchboardConstants.HTTP_OUTGOING_POOL_REMOTE_SOLR_MAX_TOTAL,
                    SwitchboardConstants.HTTP_OUTGOING_POOL_REMOTE_SOLR_MAX_TOTAL_DEFAULT));
    /* Connection pools stats */
    PoolStats stats = HTTPClient.CONNECTION_MANAGER.getTotalStats();
    prop.put("pool.general.leased", stats.getLeased());
    prop.put("pool.general.available", stats.getAvailable());
    prop.put("pool.general.pending", stats.getPending());

    stats = RemoteInstance.CONNECTION_MANAGER.getTotalStats();
    prop.put("pool.remoteSolr.leased", stats.getLeased());
    prop.put("pool.remoteSolr.available", stats.getAvailable());
    prop.put("pool.remoteSolr.pending", stats.getPending());

    /* Remote searches max loads settings */
    prop.put("remoteSearchRWIMaxLoad", sb.getConfigFloat(SwitchboardConstants.REMOTESEARCH_MAXLOAD_RWI,
            SwitchboardConstants.REMOTESEARCH_MAXLOAD_RWI_DEFAULT));
    prop.put("remoteSearchSolrMaxLoad", sb.getConfigFloat(SwitchboardConstants.REMOTESEARCH_MAXLOAD_SOLR,
            SwitchboardConstants.REMOTESEARCH_MAXLOAD_SOLR_DEFAULT));

    // parse initialization memory settings
    final String Xmx = sb.getConfig("javastart_Xmx", "Xmx600m").substring(3);
    prop.put("Xmx", Xmx.substring(0, Xmx.length() - 1));
    final String Xms = sb.getConfig("javastart_Xms", "Xms600m").substring(3);
    prop.put("Xms", Xms.substring(0, Xms.length() - 1));

    final long diskFree = sb.getConfigLong(SwitchboardConstants.RESOURCE_DISK_FREE_MIN_STEADYSTATE, 3000L);
    final long diskFreeHardlimit = sb.getConfigLong(SwitchboardConstants.RESOURCE_DISK_FREE_MIN_UNDERSHOT,
            1000L);
    final long memoryAcceptDHT = sb.getConfigLong(SwitchboardConstants.MEMORY_ACCEPTDHT, 50L);
    final boolean observerTrigger = !MemoryControl.properState();
    prop.put("diskFree", diskFree);
    prop.put("diskFreeHardlimit", diskFreeHardlimit);
    prop.put("diskFreeAutoregulate", sb.getConfigBool(SwitchboardConstants.RESOURCE_DISK_FREE_AUTOREGULATE,
            SwitchboardConstants.RESOURCE_DISK_FREE_AUTOREGULATE_DEFAULT) ? 1 : 0);
    prop.put("diskUsed", sb.getConfigLong(SwitchboardConstants.RESOURCE_DISK_USED_MAX_STEADYSTATE,
            SwitchboardConstants.RESOURCE_DISK_USED_MAX_STEADYSTATE_DEFAULT));
    prop.put("diskUsedHardlimit", sb.getConfigLong(SwitchboardConstants.RESOURCE_DISK_USED_MAX_OVERSHOT,
            SwitchboardConstants.RESOURCE_DISK_USED_MAX_OVERSHOT_DEFAULT));
    prop.put("diskUsedAutoregulate", sb.getConfigBool(SwitchboardConstants.RESOURCE_DISK_USED_AUTOREGULATE,
            SwitchboardConstants.RESOURCE_DISK_USED_AUTOREGULATE_DEFAULT) ? 1 : 0);
    prop.put("memoryAcceptDHT", memoryAcceptDHT);
    if (observerTrigger)
        prop.put("observerTrigger", "1");

    // return rewrite values for templates
    return prop;
}

From source file:com.liferay.portal.search.solr.http.BasePoolingHttpClientFactory.java

@Override
public void shutdown() {
    if (_log.isDebugEnabled()) {
        _log.debug("Shut down");
    }/*from ww  w. j  a va2  s  .c om*/

    if (_poolingClientConnectionManager == null) {
        return;
    }

    int retry = 0;

    while (retry < 10) {
        PoolStats poolStats = _poolingClientConnectionManager.getTotalStats();

        int availableConnections = poolStats.getAvailable();

        if (availableConnections <= 0) {
            break;
        }

        if (_log.isDebugEnabled()) {
            _log.debug(toString() + " is waiting on " + availableConnections + " connections");
        }

        _poolingClientConnectionManager.closeIdleConnections(200, TimeUnit.MILLISECONDS);

        try {
            Thread.sleep(500);
        } catch (InterruptedException ie) {
        }

        retry++;
    }

    _poolingClientConnectionManager.shutdown();

    _poolingClientConnectionManager = null;

    if (_log.isDebugEnabled()) {
        _log.debug(toString() + " was shut down");
    }
}

From source file:org.apache.solr.client.solrj.impl.HttpSolrClientConPoolTest.java

public void testPoolSize() throws SolrServerException, IOException {
    PoolingHttpClientConnectionManager pool = HttpClientUtil.createPoolingConnectionManager();
    final HttpSolrClient client1;
    final String fooUrl;
    {//  w w w. j  a v  a 2  s .  co m
        fooUrl = jetty.getBaseUrl().toString() + "/" + "collection1";
        CloseableHttpClient httpClient = HttpClientUtil.createClient(new ModifiableSolrParams(), pool,
                false /* let client shutdown it*/);
        client1 = getHttpSolrClient(fooUrl, httpClient);
        client1.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
    }
    final String barUrl = yetty.getBaseUrl().toString() + "/" + "collection1";

    {
        client1.setBaseURL(fooUrl);
        client1.deleteByQuery("*:*");
        client1.setBaseURL(barUrl);
        client1.deleteByQuery("*:*");
    }

    List<String> urls = new ArrayList<>();
    for (int i = 0; i < 17; i++) {
        urls.add(fooUrl);
    }
    for (int i = 0; i < 31; i++) {
        urls.add(barUrl);
    }

    Collections.shuffle(urls, random());

    try {
        int i = 0;
        for (String url : urls) {
            if (!client1.getBaseURL().equals(url)) {
                client1.setBaseURL(url);
            }
            client1.add(new SolrInputDocument("id", "" + (i++)));
        }
        client1.setBaseURL(fooUrl);
        client1.commit();
        assertEquals(17, client1.query(new SolrQuery("*:*")).getResults().getNumFound());

        client1.setBaseURL(barUrl);
        client1.commit();
        assertEquals(31, client1.query(new SolrQuery("*:*")).getResults().getNumFound());

        PoolStats stats = pool.getTotalStats();
        assertEquals("oh " + stats, 2, stats.getAvailable());
    } finally {
        for (HttpSolrClient c : new HttpSolrClient[] { client1 }) {
            HttpClientUtil.close(c.getHttpClient());
            c.close();
        }
    }
}

From source file:com.ok2c.lightmtp.impl.pool.MailIOSessionManager.java

private String formatStats(final SessionEndpoint endpoint) {
    final StringBuilder buf = new StringBuilder();
    final PoolStats totals = this.pool.getTotalStats();
    final PoolStats stats = this.pool.getStats(endpoint);
    buf.append("[total kept alive: ").append(totals.getAvailable()).append("; ");
    buf.append("address allocated: ").append(stats.getLeased() + stats.getAvailable());
    buf.append(" of ").append(stats.getMax()).append("; ");
    buf.append("total allocated: ").append(totals.getLeased() + totals.getAvailable());
    buf.append(" of ").append(totals.getMax()).append("]");
    return buf.toString();
}

From source file:org.apache.solr.client.solrj.impl.HttpSolrClientConPoolTest.java

public void testLBClient() throws IOException, SolrServerException {

    PoolingHttpClientConnectionManager pool = HttpClientUtil.createPoolingConnectionManager();
    final HttpSolrClient client1;
    int threadCount = atLeast(2);
    final ExecutorService threads = ExecutorUtil.newMDCAwareFixedThreadPool(threadCount,
            new SolrjNamedThreadFactory(getClass().getSimpleName() + "TestScheduler"));
    CloseableHttpClient httpClient = HttpClientUtil.createClient(new ModifiableSolrParams(), pool);
    try {/*  ww w .  j  a v  a 2s. co  m*/
        final LBHttpSolrClient roundRobin = new LBHttpSolrClient.Builder().withBaseSolrUrl(fooUrl)
                .withBaseSolrUrl(barUrl).withHttpClient(httpClient).build();

        List<ConcurrentUpdateSolrClient> concurrentClients = Arrays.asList(
                new ConcurrentUpdateSolrClient.Builder(fooUrl).withHttpClient(httpClient)
                        .withThreadCount(threadCount).withQueueSize(10).withExecutorService(threads).build(),
                new ConcurrentUpdateSolrClient.Builder(barUrl).withHttpClient(httpClient)
                        .withThreadCount(threadCount).withQueueSize(10).withExecutorService(threads).build());

        for (int i = 0; i < 2; i++) {
            roundRobin.deleteByQuery("*:*");
        }

        for (int i = 0; i < 57; i++) {
            final SolrInputDocument doc = new SolrInputDocument("id", "" + i);
            if (random().nextBoolean()) {
                final ConcurrentUpdateSolrClient concurrentClient = concurrentClients
                        .get(random().nextInt(concurrentClients.size()));
                concurrentClient.add(doc); // here we are testing that CUSC and plain clients reuse pool 
                concurrentClient.blockUntilFinished();
            } else {
                if (random().nextBoolean()) {
                    roundRobin.add(doc);
                } else {
                    final UpdateRequest updateRequest = new UpdateRequest();
                    updateRequest.add(doc); // here we mimic CloudSolrClient impl
                    final List<String> urls = Arrays.asList(fooUrl, barUrl);
                    Collections.shuffle(urls, random());
                    LBHttpSolrClient.Req req = new LBHttpSolrClient.Req(updateRequest, urls);
                    roundRobin.request(req);
                }
            }
        }

        for (int i = 0; i < 2; i++) {
            roundRobin.commit();
        }
        int total = 0;
        for (int i = 0; i < 2; i++) {
            total += roundRobin.query(new SolrQuery("*:*")).getResults().getNumFound();
        }
        assertEquals(57, total);
        PoolStats stats = pool.getTotalStats();
        //System.out.println("\n"+stats);
        assertEquals("expected number of connections shouldn't exceed number of endpoints" + stats, 2,
                stats.getAvailable());
    } finally {
        threads.shutdown();
        HttpClientUtil.close(httpClient);
    }
}

From source file:org.openrepose.core.services.httpclient.impl.HttpConnectionPoolServiceImpl.java

@Override
public HttpClientResponse getClient(String clientId) throws HttpClientNotFoundException {

    if (poolMap.isEmpty()) {
        defaultClientId = DEFAULT_POOL_ID;
        HttpClient httpClient = clientGenerator(DEFAULT_POOL);
        poolMap.put(defaultClientId, httpClient);
    }/*from  w ww . j  a  v  a2s.  c  o  m*/

    if (clientId != null && !clientId.isEmpty() && !isAvailable(clientId)) {
        HttpClient httpClient = clientGenerator(DEFAULT_POOL);
        poolMap.put(clientId, httpClient);
    }

    final HttpClient requestedClient;

    if (clientId == null || clientId.isEmpty()) {
        requestedClient = poolMap.get(defaultClientId);
    } else {
        if (isAvailable(clientId)) {
            requestedClient = poolMap.get(clientId);
        } else {
            throw new HttpClientNotFoundException("Pool " + clientId + "not available");
        }
    }

    String clientInstanceId = requestedClient.getParams().getParameter(CLIENT_INSTANCE_ID).toString();
    String userId = httpClientUserManager.addUser(clientInstanceId);

    PoolStats poolStats = ((PoolingClientConnectionManager) requestedClient.getConnectionManager())
            .getTotalStats();
    LOG.trace("Client requested, pool currently leased: {}, available: {}, pending: {}, max: {}",
            poolStats.getLeased(), poolStats.getAvailable(), poolStats.getPending(), poolStats.getMax());

    return new HttpClientResponseImpl(requestedClient, clientId, clientInstanceId, userId);
}

From source file:org.eclipse.aether.transport.http.HttpTransporterTest.java

@Test
public void testConnectionReuse() throws Exception {
    httpServer.addSslConnector();/*from w w  w. java 2s  .  c  om*/
    session.setCache(new DefaultRepositoryCache());
    for (int i = 0; i < 3; i++) {
        newTransporter(httpServer.getHttpsUrl());
        GetTask task = new GetTask(URI.create("repo/file.txt"));
        transporter.get(task);
        assertEquals("test", task.getDataString());
    }
    PoolStats stats = ((ConnPoolControl<?>) ((HttpTransporter) transporter).getState().getConnectionManager())
            .getTotalStats();
    assertEquals(stats.toString(), 1, stats.getAvailable());
}