Example usage for java.util.concurrent Executors newFixedThreadPool

List of usage examples for java.util.concurrent Executors newFixedThreadPool

Introduction

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

Prototype

public static ExecutorService newFixedThreadPool(int nThreads) 

Source Link

Document

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue.

Usage

From source file:com.num.mobiperf.AccountSelector.java

public AccountSelector(Context context) {
    this.context = context;
    this.checkinExecutor = Executors.newFixedThreadPool(1);
    //this.phoneUtils = PhoneUtils.getPhoneUtils();
}

From source file:kafka.deploy.utils.command.CommandRemoteOperation.java

/**
 * Executes the given commands in parallel on the remote hosts and
 * aggregates the results for the caller.
 * //  www  . j a  v  a  2s  .co  m
 * @param hostNameCommandLineMap Map with a key is the external host name
 *        and the value is the command line to execute remotely on that host
 * 
 * @return List of result types as dictated by the subclass
 * 
 * @throws RemoteOperationException Thrown on error invoking the command on
 *         one or more clients.
 */
protected void execute(Map<String, String> hostNameCommandLineMap) throws RemoteOperationException {

    ExecutorService threadPool = Executors.newFixedThreadPool(hostNameCommandLineMap.size());
    List<Future<?>> futures = new ArrayList<Future<?>>();

    for (Map.Entry<String, String> entry : hostNameCommandLineMap.entrySet()) {
        String hostName = entry.getKey();
        String commandLine = entry.getValue();

        if (logger.isDebugEnabled())
            logger.debug("Command to execute: " + commandLine);

        List<String> commandArgs = parse(commandLine);
        UnixCommand command = new UnixCommand(hostName, commandArgs);
        Callable<?> callable = getCallable(command);
        Future<?> future = threadPool.submit(callable);
        futures.add(future);
    }

    // Build up a list of all the results and/or capture the errors as they
    // occur.
    try {
        StringBuilder errors = new StringBuilder();

        for (Future<?> future : futures) {
            Throwable t = null;

            try {
                future.get();
            } catch (ExecutionException ex) {
                t = ex.getCause();
            } catch (Exception e) {
                t = e;
            }

            if (t != null) {
                if (logger.isWarnEnabled())
                    logger.warn(t, t);

                if (errors.length() > 0)
                    errors.append("; ");

                errors.append(t.getMessage());
            }
        }

        if (errors.length() > 0)
            throw new RemoteOperationException(errors.toString());
    } finally {
        threadPool.shutdown();

        try {
            threadPool.awaitTermination(60, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            if (logger.isWarnEnabled())
                logger.warn(e, e);
        }
    }
}

From source file:com.otz.transport.consumer.dispatcher.FunnelEventDispatcher.java

@PostConstruct
public void init() {
    if (loadedPlugins.getNames().contains(FUNNEL)) {
        String numberOfThreads = environment
                .getProperty(environment.getActiveProfiles()[0] + SERVICES + FUNNEL);

        int dispatchersCount = Integer.parseInt(numberOfThreads);

        executorService = Executors.newFixedThreadPool(dispatchersCount);

        //subscriptions.
        for (int i = 0; i < dispatchersCount; i++) {
            FunnelEventRunnable funnelEventRunnable = new FunnelEventRunnable(this, kafkaProperties, 200);
            listeners.add(funnelEventRunnable);
            executorService.submit(funnelEventRunnable);
        }/*from  w w  w  .j a va  2s .co m*/

    }
}

From source file:com.vmware.photon.controller.cloudstore.xenon.entity.IpLeaseServiceTest.java

@BeforeSuite
public void beforeSuite() throws Throwable {
    host = BasicServiceHost.create();// www .j a  va 2s.co m
    ServiceHostUtils.startFactoryServices(host, CloudStoreServiceGroup.FACTORY_SERVICES_MAP);

    StaticServerSet serverSet = new StaticServerSet(
            new InetSocketAddress(host.getPreferredAddress(), host.getPort()));
    xenonClient = new XenonRestClient(serverSet, Executors.newFixedThreadPool(128),
            Executors.newScheduledThreadPool(1), host);
    xenonClient.start();
}

From source file:com.vmware.photon.controller.cloudstore.xenon.entity.DhcpSubnetServiceTest.java

@BeforeSuite
public void beforeSuite() throws Throwable {
    host = BasicServiceHost.create();//from  www  . j a va2s . co m
    ServiceHostUtils.startFactoryServices(host, CloudStoreServiceGroup.FACTORY_SERVICES_MAP);

    StaticServerSet serverSet = new StaticServerSet(
            new InetSocketAddress(host.getPreferredAddress(), host.getPort()));
    xenonClient = new XenonRestClient(serverSet, Executors.newFixedThreadPool(128),
            Executors.newScheduledThreadPool(1));
    xenonClient.start();
}

From source file:org.kordamp.javatrove.example01.AppModule.java

protected void bindExecutorService() {
    bind(ExecutorService.class).toInstance(Executors.newFixedThreadPool(1));
}

From source file:com.lovejoy777sarootool.rootool.preview.IconPreview.java

public IconPreview(Activity activity) {
    mContext = activity;/* ww  w  .j  a v a  2 s.c  o m*/
    mWidth = (int) mContext.getResources().getDimension(R.dimen.item_height);
    cache = new ConcurrentHashMap<String, Bitmap>();
    pool = Executors.newFixedThreadPool(5);
    mResources = activity.getResources();
    pm = mContext.getPackageManager();

    if (mMimeTypeIconCache == null) {
        mMimeTypeIconCache = new DrawableLruCache<String>();
    }
}

From source file:eu.freme.bpt.service.AbstractService.java

public void run(final FailurePolicy failurePolicy, final int nrThreads, final Callback callback) {
    logger.info("Running service {}", this.getClass().getName());
    ExecutorService executorService = Executors.newFixedThreadPool(nrThreads);
    Unirest.setTimeouts(30000, 300000); // TODO: configurable?
    while (ioIterator.hasNext()) {
        final IO io = ioIterator.next();

        executorService.submit(() -> {
            try (final InputStream inputStream = io.getInputStream();
                    final OutputStream outputStream = io.getOutputStream()) {
                byte[] input = IOUtils.toByteArray(inputStream);
                HttpResponse<InputStream> response = Unirest.post(endpoint).headers(headers)
                        .queryString(parameters).body(input).asBinary();
                if (response.getStatus() == 200) {
                    logger.debug("Request alright.");
                    try (InputStream responseInput = response.getBody()) {
                        IOUtils.copy(responseInput, outputStream);
                        callback.onTaskComplete(io.getInputFile(), io.getOutputFile());
                    } catch (IOException e) {
                        logger.error("Error while writing response.", e);
                        callback.onTaskFails(io.getInputFile(), io.getOutputFile(),
                                "Error while writing response. " + e.getMessage());
                        if (!failurePolicy.check()) {
                            System.exit(3);
                        }/*from w ww .  ja  v a  2s.co m*/
                    }
                } else {
                    String body = IOUtils.toString(response.getBody());
                    String msg = "Error response from service " + endpoint + ": Status " + response.getStatus()
                            + ": " + response.getStatusText() + " - " + body;
                    logger.error(msg);
                    callback.onTaskFails(io.getInputFile(), io.getOutputFile(), msg);
                    if (!failurePolicy.check()) {
                        System.exit(3);
                    }
                }
            } catch (Exception e) {
                logger.error("Request to {} failed." + endpoint, e);
                callback.onTaskFails(io.getInputFile(), io.getOutputFile(),
                        "Request to " + endpoint + " failed. " + e.getMessage());
                if (!failurePolicy.check()) {
                    System.exit(3);
                }
            }
        });
    }
    executorService.shutdown();
    try {
        executorService.awaitTermination(1, TimeUnit.DAYS);
    } catch (InterruptedException e) {
        logger.warn("Waiting on termination interrupted.");
    }
    callback.onBatchComplete();
}

From source file:com.otz.transport.consumer.dispatcher.HipchatEventDispatcher.java

@PostConstruct
public void init() {
    if (loadedPlugins.getNames().contains(HIPCHAT)) {
        String numberOfThreads = environment
                .getProperty(environment.getActiveProfiles()[0] + SERVICES + HIPCHAT);

        int dispatchersCount = Integer.parseInt(numberOfThreads);

        executorService = Executors.newFixedThreadPool(dispatchersCount);

        //subscriptions.
        for (int i = 0; i < dispatchersCount; i++) {
            HtipchatNotificationRunnable htipchatNotificationRunnable = new HtipchatNotificationRunnable(this,
                    kafkaProperties, 200);
            listeners.add(htipchatNotificationRunnable);
            executorService.submit(htipchatNotificationRunnable);
        }//from ww w .ja  v  a  2s.c om

    }
}

From source file:com.predic8.membrane.examples.tests.integration.OAuth2RaceCondition.java

@Test
public void testSessionIdStateRaceCondition() throws Exception {
    HttpClient hc = HttpClientBuilder.create().build();

    login(hc);/*from ww  w. j a v a 2 s  . co m*/
    System.out.println("Logged in");
    ExecutorService executor = Executors.newFixedThreadPool(2);
    for (int i = 0; i < 10; i++) {

        //            HttpClient hc1 = HttpClientBuilder.create().build();
        //            login(hc1);
        Future<Exception>[] results = new Future[2];

        int parallelReqs = 2;
        CountDownLatch cdl = new CountDownLatch(parallelReqs);

        for (int j = 0; j < parallelReqs; j++) {
            final int fj = j;
            results[j] = executor.submit(() -> {
                try {
                    int uri = (fj % 2 == 0 ? 1 : 2);
                    String url = "http://localhost:2011/test" + uri;
                    HttpGet get = new HttpGet(url);
                    //setNoRedirects(get);
                    cdl.countDown();
                    cdl.await();
                    try (CloseableHttpResponse getRes = (CloseableHttpResponse) hc.execute(get)) {
                        assertEquals(200, getRes.getStatusLine().getStatusCode());
                        String resText = EntityUtils.toString(getRes.getEntity(), "UTF-8");
                        System.out.println("Called: Test" + uri + ".\nActual: " + resText);
                        assertTrue(resText.contains(Integer.toString(uri)));
                    }
                    return null;
                } catch (Exception e) {
                    return e;
                }
            });
        }
        for (int j = 0; j < parallelReqs; j++) {
            results[j].get();
        }

        for (int j = 0; j < parallelReqs; j++) {
            Exception e = results[j].get();
            if (e != null)
                throw new RuntimeException(e);
        }

    }
    executor.shutdown();
}