Example usage for java.util.concurrent ThreadPoolExecutor getActiveCount

List of usage examples for java.util.concurrent ThreadPoolExecutor getActiveCount

Introduction

In this page you can find the example usage for java.util.concurrent ThreadPoolExecutor getActiveCount.

Prototype

public int getActiveCount() 

Source Link

Document

Returns the approximate number of threads that are actively executing tasks.

Usage

From source file:net.darkmist.clf.Main.java

private void handleFiles(String fileNames[], int off, int len) {
    DirTraverser traverser;//from   w ww. jav  a  2  s .co  m
    Queue<File> files;
    ExecutorService executor;

    // convert fileNames to Files and put them in a Queue
    files = Util.newQueue(Util.getStringToFileConverter(), fileNames, off, len);
    //executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    executor = MoreExecutors.newCurrentThreadPool();

    traverser = new DirTraverser(files, new ExecutorFileHandler(executor, this));

    // let her rip
    traverser.run();

    // all done traversing... shutdown the executor
    executor.shutdown();
    // and wait for it
    while (!executor.isTerminated()) {
        try {
            executor.awaitTermination(STATUS_TIME, STATUS_UNIT);
        } catch (InterruptedException e) {
            logger.warn("Ignoring InterruptedException until thread pool executor stops", e);
        }
        if (logger.isDebugEnabled() && executor instanceof ThreadPoolExecutor) {
            ThreadPoolExecutor pool = (ThreadPoolExecutor) executor;
            logger.debug("ThreadPool size=" + pool.getPoolSize() + " active=" + pool.getActiveCount()
                    + " queue=" + pool.getQueue().size());
        }
    }
    executor = null;
    logger.debug("handleFiles done...");
}

From source file:com.l2jfree.gameserver.ThreadPoolManager.java

private int getTaskCount(ThreadPoolExecutor tp) {
    return tp.getQueue().size() + tp.getActiveCount();
}

From source file:eu.artofcoding.beetlejuice.spring.SpringContextHelper.java

private void stopExecutors() {
    ThreadPoolTaskExecutor springTaskExecutor = applicationContext.getBean("taskExecutor",
            ThreadPoolTaskExecutor.class);
    ThreadPoolExecutor springExecutor = springTaskExecutor.getThreadPoolExecutor();
    springExecutor.shutdownNow();// w  w  w.j  a  v a 2  s.  co m
    Map<String, ThreadPoolTaskExecutor> map = applicationContext.getBeansOfType(ThreadPoolTaskExecutor.class);
    ThreadPoolTaskExecutor t = null;
    for (String key : map.keySet()) {
        t = map.get(key);
        final ThreadPoolExecutor executor = t.getThreadPoolExecutor();
        executor.shutdownNow();
        logger.info(
                String.format("%s: active after shutdown: %d", executor.toString(), executor.getActiveCount()));
        logger.info(String.format("%s: completed after shutdown: %d", executor.toString(),
                executor.getCompletedTaskCount()));
    }
}

From source file:com.dianping.dpsf.jmx.DpsfResponsorMonitor.java

@MBeanMeta(ignore = true)
public int getActiveThreadCount(int port) {
    ThreadPoolExecutor threadPool = getThreadPool(port);
    return threadPool != null ? threadPool.getActiveCount() : -1;
}

From source file:com.alibaba.otter.node.etl.OtterController.java

public int getThreadActiveSize() {
    if (executorService instanceof ThreadPoolExecutor) {
        ThreadPoolExecutor pool = (ThreadPoolExecutor) executorService;
        return pool.getActiveCount();
    }//from w w  w .j a v  a  2 s  .  c  o m

    return 0;
}

From source file:org.jmangos.commons.threadpool.CommonThreadPoolManager.java

/**
 * @see org.jmangos.commons.threadpool.ThreadPoolManager#fillPoolStats(org.jmangos.commons.threadpool.model.ThreadPoolType)
 *//*  w  ww . j av  a 2 s . c o  m*/
@Override
public PoolStats fillPoolStats(final ThreadPoolType poolType) {

    ThreadPoolExecutor executor = null;
    switch (poolType) {
    case INSTANT:
        executor = this.instantPool;
        break;
    case SCHEDULED:
    default:
        executor = this.scheduledPool;
        break;
    }
    final PoolStats stats = new PoolStats(poolType);
    stats.setActiveCount(executor.getActiveCount());
    stats.setCompletedTaskCount(executor.getCompletedTaskCount());
    stats.setCorePoolSize(executor.getCorePoolSize());
    stats.setLargestPoolSize(executor.getLargestPoolSize());
    stats.setMaximumPoolSize(executor.getMaximumPoolSize());
    stats.setPoolSize(executor.getPoolSize());
    stats.setQueueSize(executor.getQueue().size());
    stats.setTaskCount(executor.getTaskCount());
    return stats;
}

From source file:com.kolich.boildown.Boil.java

private final void run() throws Exception {
    final Boiler.CompressionMethod method;
    final List<String> arguments;
    if (compress_ != null) {
        arguments = colonSplitter.splitToList(compress_);
        method = Boiler.CompressionMethod.COMPRESS;
    } else {// ww  w  . j  a  v a2 s  .  c o m
        arguments = colonSplitter.splitToList(decompress_);
        method = Boiler.CompressionMethod.DECOMPRESS;
    }

    if (arguments.size() != 3) {
        throw new IllegalArgumentException("Forwarder must be in the format of [port]:[host]:[port]");
    }

    // Parse the arguments.
    final int listenPort = Integer.parseInt(arguments.get(0));
    final String forwardHost = arguments.get(1);
    final int forwardPort = Integer.parseInt(arguments.get(2));

    final Boiler.Strategery strategery = getStrategery();

    final ThreadFactoryBuilder factoryBuilder = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("boiler-%d (" + listenPort + ":" + forwardHost + ":" + forwardPort + ")");

    final ThreadPoolExecutor threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(poolSize_,
            factoryBuilder.build());

    try (final ServerSocket listener = new ServerSocket(listenPort)) {
        // Run loop!
        while (true) {
            // Blocks, waiting for new connections.
            final Socket client = listener.accept();
            if (threadPool.getActiveCount() >= poolSize_) {
                // All boilers busy, forcibly hang up.
                IOUtils.closeQuietly(client);
            } else {
                // Submit the boiler to the pool, only if there's space to safely do so.
                threadPool
                        .submit(new Boiler(client, method, strategery, forwardHost, forwardPort, bufferSize_));
            }
        }
    } catch (Exception e) {
        log.error("Exception in main run-loop.", e);
    } finally {
        threadPool.shutdown();
    }
}

From source file:com.xerox.amazonws.sdb.Domain.java

/**
 * Gets attributes of given items. This method threads off the get requests and
 * aggregates the responses.//from   ww  w. j  a  va  2s.  com
 *
 * @param items the list of items to get attributes for
 * @param listener class that will be notified when items are ready
 * @throws SDBException wraps checked exceptions
 */
public void getItemsAttributes(List<String> items, ItemListener listener) throws SDBException {
    ThreadPoolExecutor pool = getThreadPoolExecutor();
    pool.setRejectedExecutionHandler(new RejectionHandler());

    Counter running = new Counter(0);
    for (String item : items) {
        while (pool.getActiveCount() == pool.getMaximumPoolSize()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
            }
        }
        synchronized (running) {
            running.increment();
        }
        pool.execute(new AttrWorker(getItem(item), running, null, listener));
        Thread.yield();
    }
    while (true) {
        if (running.getValue() == 0) {
            break;
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
        }
    }
    if (this.executor == null) {
        pool.shutdown();
    }
}

From source file:com.xerox.amazonws.sdb.Domain.java

/**
 * Gets attributes of given items. This method threads off the get requests and
 * aggregates the responses.//ww w.j a va  2 s . c  om
 *
 * @param items the list of items to get attributes for
  * @return the map of items with lists of attributes
 * @throws SDBException wraps checked exceptions
 */
public Map<String, List<ItemAttribute>> getItemsAttributes(List<String> items) throws SDBException {
    Map<String, List<ItemAttribute>> results = new Hashtable<String, List<ItemAttribute>>();
    ThreadPoolExecutor pool = getThreadPoolExecutor();
    pool.setRejectedExecutionHandler(new RejectionHandler());

    Counter running = new Counter(0);
    for (String item : items) {
        while (pool.getActiveCount() == pool.getMaximumPoolSize()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException ex) {
            }
        }
        synchronized (running) {
            running.increment();
        }
        pool.execute(new AttrWorker(getItem(item), running, results, null));
        Thread.yield();
    }
    while (true) {
        if (running.getValue() == 0) {
            break;
        }
        try {
            Thread.sleep(500);
        } catch (InterruptedException ex) {
        }
    }
    if (this.executor == null) {
        pool.shutdown();
    }
    return results;
}

From source file:de.th.wildau.dsc.sne.webserver.WebServer.java

/**
 * Web server / main constructor.//from  w  w  w. j  a  v a 2s .  c om
 * 
 * @param startArguments
 */
public WebServer(String[] startArguments) {

    loadConfiguration(startArguments);
    Log.debug(Configuration.getInstance().toString());

    Log.debug("Information about the OS: " + System.getProperty("os.name") + " - "
            + System.getProperty("os.version") + " - " + System.getProperty("os.arch"));

    if (Configuration.getConfig().getProxyHost() != null) {
        Log.debug("setup proxy configuration");
        System.setProperty("http.proxyHost", Configuration.getConfig().getProxyHost());
        System.setProperty("http.proxyPort", String.valueOf(Configuration.getConfig().getProxyPort()));
    }

    Log.debug("find supported scripting languages");
    supportedScriptLanguages = Collections.unmodifiableList(ScriptExecutor.getSupportedScriptLanguages());
    Log.debug("Supported Script Languages " + Arrays.toString(supportedScriptLanguages.toArray()));

    Log.info("instantiating web server");
    try {
        ServerSocket server = new ServerSocket(Configuration.getConfig().getServerPort());
        Log.debug("bound port " + Configuration.getConfig().getServerPort());

        int corePoolSize = Runtime.getRuntime().availableProcessors();
        int maxPoolSize = (2 * corePoolSize) + 1;
        Log.debug("core/max pool size: " + corePoolSize + "/" + maxPoolSize);
        LinkedBlockingQueue<Runnable> workerQueue = new LinkedBlockingQueue<Runnable>();
        long keepAliveTime = 30;
        /*
         * keepAliveTime - If the pool currently has more than corePoolSize
         * threads, excess threads will be terminated if they have been idle
         * for more than the keepAliveTime.
         */

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
                TimeUnit.SECONDS, workerQueue);
        threadPool.prestartAllCoreThreads();

        Socket socket = null;
        while (true) {

            try {
                socket = server.accept();
                Log.info(socket.getInetAddress().getHostName() + " client request");
                threadPool.execute(new HttpHandler(socket));
                Log.debug("current threads: " + threadPool.getActiveCount());
            } catch (final IOException ex) {
                Log.error("Connection failed!", ex);
            } catch (final RejectedExecutionException ex) {
                // XXX [sne] RejectedExecutionException
                // http://stackoverflow.com/questions/1519725/why-does-executors-newcachedthreadpool-throw-java-util-concurrent-rejectedexecut
                // http://www.javamex.com/tutorials/threads/thread_pools_queues.shtml
                // http://stackoverflow.com/questions/2001086/how-to-make-threadpoolexecutors-submit-method-block-if-it-is-saturated
                Log.error("RejectedExecutionException", ex);
                socket.close();
            } catch (final Exception ex) {
                Log.fatal("Unknown error!", ex);
            }
        }
    } catch (final IOException ex) {
        Log.fatal("Can not start the server!", ex);
        System.err.println("Can not start the server! " + ex.getMessage());
    } catch (final Exception ex) {
        Log.fatal("Unknown error!", ex);
    }
}