Example usage for java.util.concurrent ThreadPoolExecutor ThreadPoolExecutor

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

Introduction

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

Prototype

public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit,
        BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) 

Source Link

Document

Creates a new ThreadPoolExecutor with the given initial parameters.

Usage

From source file:android.concurrent.ThreadPool.java

private static ThreadPoolExecutor createThreadPoolExecutor(String poolName) {
    ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<Runnable>(DEFAULT_BLOCKING_QUEUE_SIZE);
    //      CallerRunsPolicy policy = new CallerRunsPolicy();
    ThreadPoolExecutor.DiscardPolicy policy = new ThreadPoolExecutor.DiscardPolicy();
    ThreadPoolExecutor excuter = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_TIME,
            UNIT, queue, new PoolThreadFactory(poolName), policy);
    excuter.prestartAllCoreThreads();/*w  ww.j av a  2  s. c  o  m*/
    excuter.allowCoreThreadTimeOut(true);

    return excuter;
}

From source file:com.alibaba.napoli.metamorphosis.client.extension.producer.LocalMessageStorageManager.java

public LocalMessageStorageManager(final MetaClientConfig metaClientConfig, final String path,
        final MessageRecoverer messageRecoverer) {
    super();/*from www  .j  a va2s  .  c  om*/
    this.META_LOCALMESSAGE_PATH = StringUtils.isNotBlank(path) ? path : DEFAULT_META_LOCALMESSAGE_PATH;
    this.messageRecoverer = messageRecoverer;

    if (this.META_LOCALMESSAGE_CODEC_TYPE.equals("java")) {
        this.serializer = new JavaSerializer();
        this.deserializer = new JavaDeserializer();
    } else if (this.META_LOCALMESSAGE_CODEC_TYPE.equals("hessian1")) {
        this.serializer = new Hessian1Serializer();
        this.deserializer = new Hessian1Deserializer();
    } else {
        throw new UnknowCodecTypeException(this.META_LOCALMESSAGE_CODEC_TYPE);
    }

    // ?RecoverThreadCount
    this.threadPoolExecutor = new ThreadPoolExecutor(metaClientConfig.getRecoverThreadCount(),
            metaClientConfig.getRecoverThreadCount(), 60, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(100), new NamedThreadFactory("SendRecover-thread"),
            new ThreadPoolExecutor.CallerRunsPolicy());

    this.makeDataDir();
    this.loadStores();

    // ????,??topic???
    this.scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            log.info("????...");
            LocalMessageStorageManager.this.recover();
        }
    }, 0, metaClientConfig.getRecoverMessageIntervalInMills(), TimeUnit.MILLISECONDS);

}

From source file:esg.node.core.ESGQueue.java

public ESGQueue(DataNodeComponent handler, ESGQueueController qController, ESGBatchController bController) {
    this(handler,
            new ThreadPoolExecutor(2, 20, 10L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(1000),
                    new ESGGroupedThreadFactory(handler.getName()), new ESGRejectPolicy(handler.getName())),
            qController, bController);//  w  w w  . j  a  va 2  s  .c  om
}

From source file:org.lilyproject.util.hbase.LocalHTable.java

public LocalHTable(Configuration conf, byte[] tableName) throws IOException {
    this.conf = conf;
    this.tableName = tableName;
    this.tableNameString = Bytes.toString(tableName);
    this.pool = getHTablePool(conf);

    // HTable internally has an ExecutorService. I have noticed that many of the HBase operations that Lily
    // performs don't make use of this ES, since they are not plain put or batch operations. Thus, for the
    // operations that do make use of it, they use the ExecutorServices of many different HTable instances,
    // leading to very little thread re-use and many very short-lived threads. Therefore, we switch the
    // ExecutorService instance in HBase by a shared one, which requires modifying a private variable.
    // (seems like this is improved in HBase trunk)

    synchronized (this) {
        if (EXECUTOR_SERVICE == null) {
            int maxThreads = Integer.MAX_VALUE;
            log.debug("Creating ExecutorService for HTable with max threads = " + maxThreads);

            EXECUTOR_SERVICE = new ThreadPoolExecutor(1, maxThreads, 60, TimeUnit.SECONDS,
                    new SynchronousQueue<Runnable>(), new CustomThreadFactory("hbase-batch", null, true),
                    new WaitPolicy());
            EXECUTOR_SERVICE_SHUTDOWN_PROTECTED = new ShutdownProtectedExecutor(EXECUTOR_SERVICE);

            try {
                POOL_FIELD = HTable.class.getDeclaredField("pool");
                POOL_FIELD.setAccessible(true);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }/*from ww  w  .j  a  v  a2s.  c  o m*/
        }
    }

    // Test the table is accessible
    runNoIE(new TableRunnable<Object>() {
        @Override
        public Object run(HTableInterface table) throws IOException {
            return null;
        }
    });
}

From source file:org.alfresco.bm.server.EventController.java

/**
 * Construct the controller/*from  w w  w  . j  a v a2s.  c  om*/
 * 
 * @param driverId          the ID of the driver controlling the events
 * @param testRunFqn        the fully qualified name of the test run
 * @param testDAO           the test DAO for accessing low level data
 * @param testRunId         the ID of the test run being controlled
 * @param eventService      the source of events that will be pushed for execution
 * @param eventProducers    the registry of producers of events
 * @param eventProcessors   the registry of processors for events
 * @param resultService     the service used to store and retrieve event results
 * @param sessionService    the service to carry session IDs between events
 * @param logService        the service to record log messages for the end user
 * @param threadCount       the number of threads available to the processor
 */
public EventController(String driverId, String testRunFqn, EventService eventService,
        EventProducerRegistry eventProducers, EventProcessorRegistry eventProcessors,
        ResultService resultService, SessionService sessionService, TestRunLogService logService,
        int threadCount) {
    thread = new Thread(new ThreadGroup(testRunFqn), this, testRunFqn + "-Controller");
    thread.setDaemon(false); // Requires explicit shutdown

    this.driverId = driverId;
    this.testRunFqn = testRunFqn;
    this.eventService = eventService;
    this.eventProducers = eventProducers;
    this.eventProcessors = eventProcessors;
    this.resultService = resultService;
    this.sessionService = sessionService;
    this.logService = logService;
    this.threadCount = threadCount;
    // Configure threads
    CustomizableThreadFactory threadFactory = new CustomizableThreadFactory(testRunFqn + "-");
    threadFactory.setThreadGroup(thread.getThreadGroup());
    threadFactory.setDaemon(true);
    // Configure work queue
    SynchronousQueue<Runnable> queue = new SynchronousQueue<Runnable>(true);
    // Configure executor
    RejectedExecutionHandler abortPolicy = new ThreadPoolExecutor.CallerRunsPolicy();
    executor = new ThreadPoolExecutor(threadCount, threadCount, 60, TimeUnit.SECONDS, queue, threadFactory,
            abortPolicy);

    setRunning(true);
}

From source file:com.splicemachine.derby.stream.control.ControlDataSet.java

@Override
public DataSet<V> union(DataSet<V> dataSet) {
    ThreadPoolExecutor tpe = null;
    try {/*from ww  w  . j  av a  2 s.  c  o m*/

        ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("union-begin-query-%d")
                .setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                    @Override
                    public void uncaughtException(Thread t, Throwable e) {
                        e.printStackTrace();
                    }
                }).build();
        tpe = new ThreadPoolExecutor(2, 2, 60, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), factory,
                new ThreadPoolExecutor.CallerRunsPolicy());
        tpe.allowCoreThreadTimeOut(false);
        tpe.prestartAllCoreThreads();
        Future<Iterator<V>> leftSideFuture = tpe.submit(new NonLazy(iterator));
        Future<Iterator<V>> rightSideFuture = tpe.submit(new NonLazy(((ControlDataSet<V>) dataSet).iterator));

        return new ControlDataSet<>(Iterators.concat(leftSideFuture.get(), rightSideFuture.get()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (tpe != null)
            tpe.shutdown();
    }
}

From source file:org.sapia.soto.util.concurrent.ExecutorService.java

/**
 * Internal factory method that creates the executor instance. Subclass may override this method to
 * change the actual executor implementation used.
 *
 * @param aThreadFactory The thread factory to use for the executor.
 * @return The created thead pool executor instance.
 *///from   w  w w  .j  a v a2 s .  c  om
protected ThreadPoolExecutor createExecutor(ThreadFactory aThreadFactory) {
    // Create the queue of pending tasks
    BlockingQueue queue;
    if (_taskQueueSize == 0) {
        queue = new SynchronousQueue();
    } else {
        queue = new ArrayBlockingQueue(_taskQueueSize);
    }

    return new ThreadPoolExecutor(_coreThreadPoolSize, _maximumThreadPoolSize, _threadKeepAliveTime,
            TimeUnit.MILLISECONDS, queue, aThreadFactory, _rejectedExecutionHandler);
}

From source file:hudson.plugins.active_directory.ActiveDirectoryUnixAuthenticationProvider.java

public ActiveDirectoryUnixAuthenticationProvider(ActiveDirectorySecurityRealm realm) {
    this.site = realm.site;
    this.domains = realm.domains;
    this.groupLookupStrategy = realm.getGroupLookupStrategy();
    this.descriptor = realm.getDescriptor();
    this.cache = realm.cache;

    if (cache == null) {
        this.cache = new CacheConfiguration(0, 0);
    }//from  w  ww . j a va2 s . c om

    // On startup userCache and groupCache are not created and cache is different from null
    if (cache.getUserCache() == null || cache.getGroupCache() == null) {
        this.cache = new CacheConfiguration(cache.getSize(), cache.getTtl());
    }

    this.userCache = cache.getUserCache();
    this.groupCache = cache.getGroupCache();

    this.threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveTime,
            TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(queueSize),
            new NamingThreadFactory(new DaemonThreadFactory(), "ActiveDirectory.updateUserCache"),
            new ThreadPoolExecutor.DiscardPolicy());

    Map<String, String> extraEnvVarsMap = ActiveDirectorySecurityRealm.EnvironmentProperty
            .toMap(realm.environmentProperties);
    props.put(LDAP_CONNECT_TIMEOUT, System.getProperty(LDAP_CONNECT_TIMEOUT, DEFAULT_LDAP_CONNECTION_TIMEOUT));
    props.put(LDAP_READ_TIMEOUT, System.getProperty(LDAP_READ_TIMEOUT, DEFAULT_LDAP_READ_TIMEOUT));
    // put all the user defined properties into our context environment replacing any mappings that already exist.
    props.putAll(extraEnvVarsMap);
}

From source file:com.alibaba.otter.manager.biz.monitor.impl.GlobalMonitor.java

@Override
public void afterPropertiesSet() throws Exception {
    nThreads = nThreads <= 0 ? DEFAULT_THREADS : nThreads;
    executor = new ThreadPoolExecutor(nThreads, nThreads, 0, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<Runnable>(nThreads * 2), new NamedThreadFactory("global monitor", false),
            new ThreadPoolExecutor.CallerRunsPolicy());

}