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) 

Source Link

Document

Creates a new ThreadPoolExecutor with the given initial parameters, the default thread factory and the default rejected execution handler.

Usage

From source file:com.nextgis.mobile.map.MapBase.java

/**
 * The base map class//from  w  w  w .ja  v a  2  s  .com
 */

public MapBase(Context context) {
    super(context);

    mName = context.getString(R.string.default_map_name);
    mNewId = 0;
    mListeners = new ArrayList<MapEventListener>();
    mLayers = new ArrayList<Layer>();

    mCPUTotalCount = Runtime.getRuntime().availableProcessors() - 1;
    if (mCPUTotalCount < 1)
        mCPUTotalCount = 1;
    mContinueDrawing = false;

    newtworkUtil = new NetworkUtil(context);

    createHandler();

    //initialise display
    mDisplay = new GISDisplay(context);

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    File defaultPath = context.getExternalFilesDir(PREFS_MAP);
    mMapPath = new File(sharedPreferences.getString(KEY_PREF_MAP_PATH, defaultPath.getPath()));

    mDrawWorkQueue = new LinkedBlockingQueue<Runnable>();
    mDrawThreadPool = new ThreadPoolExecutor(1, mCPUTotalCount, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT,
            mDrawWorkQueue);

    setKeepScreenOn(true);
}

From source file:com.jivesoftware.os.upena.uba.service.Nanny.java

public Nanny(PasswordStore passwordStore, UpenaClient upenaClient, RepositoryProvider repositoryProvider,
        InstanceDescriptor instanceDescriptor, InstancePath instancePath,
        DeployableValidator deployableValidator, DeployLog deployLog, HealthLog healthLog,
        DeployableScriptInvoker invokeScript, UbaLog ubaLog,
        Cache<String, Boolean> haveRunConfigExtractionCache) {

    this.passwordStore = passwordStore;
    this.upenaClient = upenaClient;
    this.repositoryProvider = repositoryProvider;
    this.instanceDescriptor = new AtomicReference<>(instanceDescriptor);
    this.instancePath = instancePath;
    this.deployableValidator = deployableValidator;
    this.deployLog = deployLog;
    this.healthLog = healthLog;
    this.invokeScript = invokeScript;
    this.ubaLog = ubaLog;
    linkedBlockingQueue = new LinkedBlockingQueue<>(10);
    threadPoolExecutor = new ThreadPoolExecutor(1, 1, 1000, TimeUnit.MILLISECONDS, linkedBlockingQueue);
    boolean exists = instancePath.deployLog().exists();
    LOG.info("Stats script for {} exists == {}", instanceDescriptor, exists);
    redeploy = new AtomicBoolean(!exists);
    destroyed = new AtomicBoolean(false);
    this.haveRunConfigExtractionCache = haveRunConfigExtractionCache;
}

From source file:org.apache.activemq.JmsConnectionStartStopTest.java

public void testConcurrentSessionCreateWithStart() throws Exception {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(50, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
            new SynchronousQueue<Runnable>());
    final Vector<Throwable> exceptions = new Vector<Throwable>();
    final Random rand = new Random();
    Runnable createSessionTask = new Runnable() {
        @Override//from   w w w .  j  a  v a 2s  .  com
        public void run() {
            try {
                TimeUnit.MILLISECONDS.sleep(rand.nextInt(10));
                stoppedConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            } catch (Exception e) {
                exceptions.add(e);
            }
        }
    };

    Runnable startStopTask = new Runnable() {
        @Override
        public void run() {
            try {
                TimeUnit.MILLISECONDS.sleep(rand.nextInt(10));
                stoppedConnection.start();
                stoppedConnection.stop();
            } catch (Exception e) {
                exceptions.add(e);
            }
        }
    };

    for (int i = 0; i < 1000; i++) {
        executor.execute(createSessionTask);
        executor.execute(startStopTask);
    }

    executor.shutdown();
    assertTrue("executor terminated", executor.awaitTermination(30, TimeUnit.SECONDS));
    assertTrue("no exceptions: " + exceptions, exceptions.isEmpty());
}

From source file:com.fusesource.forge.jmstest.benchmark.command.BenchmarkCoordinator.java

public void start() {
    synchronized (started) {
        if (!started) {
            log().debug("Starting Benchmark Coordinator.");
            ReleaseManager.getInstance().register(this);
            benchmarks = new HashMap<String, BenchmarkRunner>();
            executor = new ThreadPoolExecutor(1, 1, 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
            started = true;//from w ww. j a va  2s .c om
        }
    }
}

From source file:org.esigate.test.cases.PerformanceTestCase.java

/**
 * Execute la tache avec plusieurs Threads
 * //w  w  w .  ja va 2  s .  c o  m
 * @param request
 * @return
 * @throws Exception
 */
private long execute(HttpGetRequestRunnable request, int numberOfRequests, int threads) throws Exception {
    connectionManager = new PoolingHttpClientConnectionManager();
    httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).setMaxConnTotal(threads)
            .setMaxConnPerRoute(threads).setDefaultRequestConfig(
                    RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).build())
            .build();
    // Warm up
    request.run();

    BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threads, threads, 5, TimeUnit.SECONDS, queue);

    long start = System.currentTimeMillis();
    threadPool.prestartAllCoreThreads();
    for (int i = 0; i < numberOfRequests; i++) {
        threadPool.submit(request);
    }
    threadPool.shutdown();

    // wait maximum 20 s
    threadPool.awaitTermination(200, TimeUnit.SECONDS);
    connectionManager.shutdown();

    if (request.exception != null) {
        throw new AssertionFailedError(
                "Exception for request " + request.url + " after " + request.count + " requests",
                request.exception);
    }
    if (threadPool.getCompletedTaskCount() < threadPool.getTaskCount()) {
        // All task were not executed
        String msg = request.url + " : Only " + threadPool.getCompletedTaskCount() + "/"
                + threadPool.getTaskCount() + " have been renderered " + " => Maybe a performance issue";
        threadPool.shutdownNow();
        fail(msg);
    }

    long end = System.currentTimeMillis();
    long execTime = end - start;
    LOG.debug("Executed request " + request.url + " " + numberOfRequests + " times with " + threads
            + " threads in " + execTime + "ms");
    return execTime;

}

From source file:org.esigate.extension.parallelesi.Esi.java

@Override
public void init(Driver driver, Properties properties) {
    driver.getEventManager().register(EventManager.EVENT_RENDER_PRE, this);

    driver.getEventManager().register(Surrogate.EVENT_SURROGATE_CAPABILITIES, new IEventListener() {
        @Override/*  w w w . ja va2  s . c  o m*/
        public boolean event(EventDefinition id, Event event) {
            CapabilitiesEvent capEvent = (CapabilitiesEvent) event;
            for (String capability : CAPABILITIES) {
                capEvent.getCapabilities().add(capability);
            }
            return true;
        }
    });

    // Load configuration
    this.maxThreads = THREADS.getValue(properties);
    this.idle = IDLE.getValue(properties);

    if (this.maxThreads == 0) {
        this.executor = null;
        LOG.info("Linear ESI processing enabled.");
    } else {
        this.executor = new ThreadPoolExecutor(0, this.maxThreads, this.idle, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());

        LOG.info("Multi-threaded ESI processing enabled. Thread limit: {}, max idle {}.",
                String.valueOf(this.maxThreads), String.valueOf(this.idle));
    }

}

From source file:com.pinterest.rocksplicator.controller.WorkerPoolTest.java

@Test
public void testCancelSingleTask() throws Exception {
    Semaphore idleWorkersSemaphore = new Semaphore(0);
    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(1));
    WorkerPool workerPool = new WorkerPool(threadPoolExecutor, idleWorkersSemaphore, new TaskQueue() {
    });//from   ww w . j a v  a2s  .com
    Task task = getSleepIncrementTask();
    workerPool.assignTask(task);
    Thread.sleep(10);
    workerPool.abortTask(task.clusterName);
    Thread.sleep(100);
    Assert.assertEquals(1, idleWorkersSemaphore.availablePermits());
}

From source file:org.mule.config.pool.DefaultThreadPoolFactory.java

protected ThreadPoolExecutor internalCreatePool(String name, ThreadingProfile tp, BlockingQueue buffer) {
    return new ThreadPoolExecutor(Math.min(tp.getMaxThreadsIdle(), tp.getMaxThreadsActive()),
            tp.getMaxThreadsActive(), tp.getThreadTTL(), TimeUnit.MILLISECONDS, buffer);
}

From source file:org.rifidi.edge.core.sensors.sessions.AbstractServerSocketSensorSession.java

@Override
protected void _connect() throws IOException {
    if (serverSocketPort < 1) {
        logger.info("Not starting server socket, since port < 1");
        return;// www  .j  a va  2s  .  c om
    }

    if (getStatus() == SessionStatus.CONNECTING || getStatus() == SessionStatus.PROCESSING) {
        logger.warn("Session already started");
        return;
    }
    setStatus(SessionStatus.CONNECTING);

    // create a new executor service that will handle each new request. Use
    // SynchronousQueue so that tasks will be rejected if there is no free
    // worker thread available
    executorService = new ThreadPoolExecutor(0, maxNumSensors, 5, TimeUnit.MINUTES,
            new SynchronousQueue<Runnable>());

    // open up server socket
    try {
        serverSocket = new ServerSocket(serverSocketPort);
    } catch (IOException e) {
        logger.error("Cannot start Alient Autonomous Sensor");
        disconnect();
        throw e;
    }
    logger.info(sensor.getID() + " listening on port " + serverSocket.getLocalPort()
            + ".  Maximum number of concurrent readers supported: " + maxNumSensors);
    setStatus(SessionStatus.PROCESSING);

    // while session is not closed, process each request
    while (!executorService.isShutdown()) {
        try {
            // wait on a new request
            Socket clientSocket = serverSocket.accept();
            logger.info("Accepted client at " + clientSocket.getInetAddress());

            // give the socket to the handler to do the dirty work
            ServerSocketSensorSessionReadThread handler = new ServerSocketSensorSessionReadThread(clientSocket,
                    getMessageParsingStrategyFactory(), getMessageProcessingStrategyFactory());
            try {
                executorService.execute(handler);
            } catch (RejectedExecutionException e) {
                logger.warn("Cannot create a handler thread for socket " + clientSocket.getInetAddress(), e);
                clientSocket.close();
            }
        } catch (IOException e) {
            // print an error message if we weren't the ones who caused the
            // problem
            if (!executorService.isShutdown()) {
                logger.error("Failed to start Alien Autonomous Handler", e);
            }
        }
    }
    logger.info("Stopping " + sensor.getID());
    setStatus(SessionStatus.CREATED);

}

From source file:IndexService.IndexServer.java

public IndexServer(Configuration conf2) {
    initialize(conf2);/*from w  w  w  .j a  v a 2s.c o m*/
    MDC_check_interval = conf.getInt("se.indexer.MDC_interval", 10000);
    DPM_check_interval = conf.getInt("se.indexer.DPM_interval", 10000);
    TQM_check_interval = conf.getInt("se.indexer.TQM_interval", 5000);
    IPM_check_merge_interval = conf.getInt("se.indexer.IPM_merge_interval", 3600 * 1000);
    mergeindexfilelimit = conf.getInt("mergeindexfilelimit", 200);

    Indexer_max_jobnum = conf.getInt("indexer.max.jobnum", 10);
    poolExecutor = new ThreadPoolExecutor(Indexer_max_jobnum, Indexer_max_jobnum * 2, 30, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());
}