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, RejectedExecutionHandler handler) 

Source Link

Document

Creates a new ThreadPoolExecutor with the given initial parameters and Executors#defaultThreadFactory default thread factory .

Usage

From source file:com.openteach.diamond.service.request.HSFNetworkRequestHandler.java

@Override
public void initialize() {
    super.initialize();
    queue = new ArrayBlockingQueue<Runnable>(resourceConfig.getQueueSize());
    threadpool = new ThreadPoolExecutor(resourceConfig.getMinThreadCount(), resourceConfig.getMaxThreadCount(),
            resourceConfig.getKeepAliveTime(), TimeUnit.SECONDS, queue,
            new CommonThreadFactory("HSF-Request-Handler-Thread", null, true));
}

From source file:org.apache.hadoop.hdfs.server.datanode.DataXceiverThreadPool.java

/**
 * Create a pool of threads to do disk IO.
 * /*from   w  w  w .  jav a 2s.co m*/
 * @param conf The configuration
 * @param tg The ThreadGroup of all the executor threads
 * @param maxXceiverCount The max number of threads that can do IO.
 */
DataXceiverThreadPool(final Configuration conf, final ThreadGroup tg, final int maxXceiverCount) {

    ThreadFactory threadFactory = new ThreadFactory() {
        int counter = 0;

        @Override
        public Thread newThread(Runnable r) {
            int thisIndex;
            synchronized (this) {
                thisIndex = counter++;
            }
            Thread t = new Thread(tg, r);
            t.setName("disk io thread #" + thisIndex);
            t.setDaemon(true);
            return t;
        }
    };

    executor = new ThreadPoolExecutor(maxXceiverCount - 1, maxXceiverCount, THREADS_KEEP_ALIVE_SECONDS,
            TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), threadFactory);

    // This can reduce the number of running threads
    executor.allowCoreThreadTimeOut(true);
}

From source file:com.doculibre.constellio.feedprotocol.FeedServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    System.out.println("FeedServlet Started");

    int feedProcessorThreads = ConstellioSpringUtils.getFeedProcessorThreads();
    threadPoolExecutor = new ThreadPoolExecutor(feedProcessorThreads, feedProcessorThreads, 5, TimeUnit.MINUTES,
            new ArrayBlockingQueue<Runnable>(feedProcessorThreads + 1),
            new ThreadPoolExecutor.CallerRunsPolicy());
}

From source file:com.nextgis.maplib.display.SimpleFeatureRenderer.java

@Override
public void runDraw(final GISDisplay display) {
    GeoEnvelope env = display.getBounds();
    final VectorLayer vectorLayer = (VectorLayer) mLayer;
    GeoEnvelope layerEnv = vectorLayer.getExtents();

    if (!env.intersects(layerEnv)) {
        vectorLayer.onDrawFinished(vectorLayer.getId(), 1);
        return;//w  w w  . j av  a2s.  c om
    }

    //add drawing routine
    final List<VectorCacheItem> cache = vectorLayer.getVectorCache();

    //TODO: more than one thread for drawing (divide the geometry cache array on several parts)
    //TODO: think about display syncronization in drawing points/lines/polygons

    mDrawThreadPool = new ThreadPoolExecutor(1, 1, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT,
            new LinkedBlockingQueue<Runnable>(), new RejectedExecutionHandler() {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    try {
                        executor.getQueue().put(r);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        //throw new RuntimeException("Interrupted while submitting task", e);
                    }
                }
            });

    if (cache.size() == 0) {
        vectorLayer.onDrawFinished(vectorLayer.getId(), 1);
        return;
    }

    mDrawThreadPool.execute(new Runnable() {
        @Override
        public void run() {
            android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

            for (int i = 0; i < cache.size(); i++) {
                VectorCacheItem item = cache.get(i);

                GeoGeometry geometry = item.getGeoGeometry();
                mStyle.onDraw(geometry, display);

                synchronized (mLayer) {
                    float percent = (float) i / cache.size();
                    vectorLayer.onDrawFinished(vectorLayer.getId(), percent);
                }

                vectorLayer.onDrawFinished(vectorLayer.getId(), 1);
                //Log.d(TAG, "percent: " + percent + " complete: " + mDrawThreadPool.getCompletedTaskCount() + " task count: " + mDrawThreadPool.getTaskCount());
            }
        }
    });
}

From source file:metlos.executors.batch.BatchCpuThrottlingExecutorTest.java

@Test
public void maxUsage_SingleThreaded() throws Exception {
    NamingThreadFactory factory = new NamingThreadFactory();
    ThreadPoolExecutor e = new ThreadPoolExecutor(1, 1, 0, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(),
            factory);//from www  .  j  a va 2  s  .  c  o  m
    e.prestartAllCoreThreads();

    List<Future<?>> payloadResults = new ArrayList<Future<?>>();

    long startTime = System.nanoTime();

    //create load
    for (int i = 0; i < NOF_JOBS; ++i) {
        Future<?> f = e.submit(new Payload());
        payloadResults.add(f);
    }

    //wait for it all to finish
    for (Future<?> f : payloadResults) {
        f.get();
    }

    long endTime = System.nanoTime();

    long time = endTime - startTime;
    LOG.info("MAX Singlethreaded test took " + (time / 1000.0 / 1000.0) + "ms");

    ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
    long cpuTime = 0;
    for (Thread t : factory.createdThreads) {
        long threadCpuTime = threadBean.getThreadCpuTime(t.getId());
        LOG.info(t.getName() + ": " + threadCpuTime + "ns");
        cpuTime += threadCpuTime;
    }

    float actualUsage = (float) cpuTime / time;

    LOG.info("MAX Singlethreaded overall usage: " + actualUsage);
}

From source file:com.sm.replica.server.ReplicaServerHandler.java

private void init() {
    if (Runtime.getRuntime().availableProcessors() > maxThreads)
        this.maxThreads = Runtime.getRuntime().availableProcessors();
    if (maxQueue < maxThreads * 1000)
        maxQueue = maxThreads * 1000;//from w  w  w  . j  ava2 s.  co m
    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(maxQueue);
    threadPools = new ThreadPoolExecutor(maxThreads, maxThreads, 30, TimeUnit.SECONDS, queue,
            new ThreadPoolFactory("Replica"));
}

From source file:com.oneops.util.ReliableExecutor.java

public ReliableExecutor(int threadPoolSize, boolean doSyncOnRejection) {
    this.threadPoolSize = threadPoolSize;
    RejectedExecutionHandler handler;
    if (doSyncOnRejection) {
        handler = new ThreadPoolExecutor.CallerRunsPolicy();
    } else {//w  w w.  j a va2s.  c  o m
        handler = new ThreadPoolExecutor.AbortPolicy();
    }
    executors = new ThreadPoolExecutor(0, threadPoolSize, 60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>(), handler);
}

From source file:com.sm.replica.server.grizzly.ReplicaServerFilter.java

protected void init() {
    if (Runtime.getRuntime().availableProcessors() > maxThreads)
        this.maxThreads = Runtime.getRuntime().availableProcessors();
    if (maxQueue < maxThreads * 1000)
        maxQueue = maxThreads * 1000;/*from   ww  w  .  j a v a  2 s . c  o  m*/
    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>(maxQueue);
    threadPools = new ThreadPoolExecutor(maxThreads, maxThreads, 30, TimeUnit.SECONDS, queue,
            new ThreadPoolFactory("Replica"));
}

From source file:com.indeed.imhotep.web.config.SpringConfiguration.java

@Bean(destroyMethod = "shutdown")
public ExecutorService executorService() {
    return new ThreadPoolExecutor(3, 10, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(100),
            new NamedThreadFactory("IQL-Worker"));
}

From source file:com.taobao.tddl.common.sync.RowBasedReplicater.java

public void init() {
    /**//from w  ww .  ja va  2s .  c  o  m
     * CallerRunsPolicy: execute
     */
    replicationExecutor = new ThreadPoolExecutor(threadPoolSize, threadPoolSize, 0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<Runnable>(workQueueSize), new ThreadPoolExecutor.CallerRunsPolicy());

    /**
     * LogDiscardPolicy
     */
    deleteSyncLogExecutor = new ThreadPoolExecutor(1, 2, 0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<Runnable>(10), new RejectedExecutionHandler() {
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    logger.warn("A DeleteSyncLogTask discarded");
                }
            });
    updateSyncLogExecutor = new ThreadPoolExecutor(1, 2, 0L, TimeUnit.MILLISECONDS,
            new ArrayBlockingQueue<Runnable>(10), new RejectedExecutionHandler() {
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    logger.warn("A UpdateSyncLogTask discarded");
                }
            });

    /**
     * 
     */
    final BucketTaker<RowBasedReplicationContext> deleteBucketTaker = new BucketTaker<RowBasedReplicationContext>(
            deleteSyncLogExecutor) {
        @Override
        public Runnable createTakeAwayTask(Collection<RowBasedReplicationContext> list) {
            return new DeleteSyncLogTask(list);
        }

    };
    final BucketTaker<RowBasedReplicationContext> updateBucketTaker = new BucketTaker<RowBasedReplicationContext>(
            updateSyncLogExecutor) {

        @Override
        public Runnable createTakeAwayTask(Collection<RowBasedReplicationContext> list) {
            return new UpdateSyncLogTask(list);
        }

    };
    deleteBucketSwitcher = new NoStrictBucketSwitcher<RowBasedReplicationContext>(deleteBucketTaker,
            DEFAULT_BATCH_DELETE_SIZE);
    updateBucketSwitcher = new NoStrictBucketSwitcher<RowBasedReplicationContext>(updateBucketTaker,
            DEFAULT_BATCH_UPDATE_SIZE);

    TDDLMBeanServer.registerMBean(this, "Replicater"); //JMX
}