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.microsoft.azure.storage.util.KVCredentials.java

/**
 * Creates the access token//w ww.ja va2  s . co  m
 * 
 * @param authorization
 *            The authorization from the service
 * @param resource
 *            The resource being accessed
 * @param clientId
 *            The ClientID for this application
 * @param clientKey
 *            The Client Secret for this application
 * @return The access token to use to authenticate to the service
 */
private static AuthenticationResult getAccessTokenFromClientCredentials(String authorization, String resource,
        String clientId, String clientKey) {
    AuthenticationContext context = null;
    AuthenticationResult result = null;
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        context = new AuthenticationContext(authorization, false, service);
        ClientCredential credentials = new ClientCredential(clientId, clientKey);
        Future<AuthenticationResult> future = context.acquireToken(resource, credentials, null);
        result = future.get();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        service.shutdown();
    }

    if (result == null) {
        throw new RuntimeException("authentication result was null");
    }
    return result;
}

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

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

        int dispatchersCount = Integer.parseInt(numberOfThreads);

        executorService = Executors.newFixedThreadPool(dispatchersCount);

        //subscriptions.
        for (int i = 0; i < dispatchersCount; i++) {
            SmsEventRunnable smsEventRunnable = new SmsEventRunnable(this, kafkaProperties, 200);
            listeners.add(smsEventRunnable);
            executorService.submit(smsEventRunnable);
        }/*from  w w w . j a  va2  s.  c o m*/

    }
}

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

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

        int dispatchersCount = Integer.parseInt(numberOfThreads);

        executorService = Executors.newFixedThreadPool(dispatchersCount);

        //subscriptions.
        for (int i = 0; i < dispatchersCount; i++) {
            EmailEventRunnable emailEventRunnable = new EmailEventRunnable(this, kafkaProperties, 200);
            listeners.add(emailEventRunnable);
            executorService.submit(emailEventRunnable);
        }//from   www . ja v  a2s  .  c  o m

    }
}

From source file:demo.vmware.commands.CommandGetAllRegions.java

/**
 * Retrieve the contents for all regions, one region per task executor
 *//* w  w w  .  j  a  va  2 s  .  c  o m*/
@Override
public CommandResult run(ConfigurableApplicationContext mainContext, List<String> parameters) {
    // Use the template for this meaning we can only fetch the whole contents of any region we have a template for
    // CommandGetCounts goes right to the cache so it may list more regions
    Map<String, GemfireTemplate> allRegionTemplates = CommandRegionUtils.getAllGemfireTemplates(mainContext);

    // use the Java executor service because of it's awesome invokeAll method.
    ExecutorService taskExecutor = Executors.newFixedThreadPool(allRegionTemplates.size());
    Collection tasks = new ArrayList<RegionFetcher>();

    CommandTimer timer = new CommandTimer();
    for (String key : allRegionTemplates.keySet()) {
        GemfireTemplate oneTemplate = allRegionTemplates.get(key);
        if (parallelFetch) {
            tasks.add(new RegionFetcher(oneTemplate.getRegion().getName(), 0, oneTemplate));
        } else {
            // don't write anything out and don't capture results
            fetchOneRegion(oneTemplate.getRegion().getName(), 5, oneTemplate);
        }
    }
    if (parallelFetch) {
        // invokeAll() returns when all tasks are complete
        try {
            List<Future<?>> futures = taskExecutor.invokeAll(tasks);
            taskExecutor.shutdown();
            LOG.info("Fetched " + futures.size() + " regions in threads");
            // the futures hold the results at this point futures.get(X).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    timer.stop();
    return new CommandResult(null, "Loading all regions took " + timer.getTimeDiffInSeconds() + " seconds");
}

From source file:com.mobius.software.mqtt.performance.runner.ScenarioRunner.java

public void start() throws InterruptedException {
    List<RequestWorker> workers = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(requests.size());
    for (ScenarioRequest request : requests)
        workers.add(new RequestWorker(request, latch));

    ExecutorService service = Executors.newFixedThreadPool(workers.size());
    for (RequestWorker worker : workers)
        service.submit(worker);/*from  w  w w .  j ava  2  s  .co m*/
    latch.await();

    service.shutdownNow();
}

From source file:com.baidu.rigel.biplatform.tesseract.datasource.impl.SqlDataSourceManagerImpl.java

/**
 * ?????//from   w w w  . j  a va  2s . co m
 * 
 * @return ???
 */
public static synchronized SqlDataSourceManagerImpl getInstance() {
    if (instance == null) {
        instance = new SqlDataSourceManagerImpl();
        if (instance.checkUnusedDataSourceThread == null) {
            instance.checkUnusedDataSourceThread = Executors.newFixedThreadPool(1);

            //                instance.checkUnusedDataSourceThread.submit(() -> {
            //                    while (true) {
            //                        instance.log.info("check datasource unused begin..");
            //                        instance.expireDataSource();
            //                        instance.log.info("check datasource unused end..");
            //                        try {
            //                            Thread.sleep(60000);
            //                        } catch (Exception e) {
            //                            e.printStackTrace();
            //                        }
            //                    }
            //                });

            instance.checkUnusedDataSourceThread.submit(new Runnable() {
                public void run() {
                    while (true) {
                        instance.log.info("check datasource unused begin..");
                        instance.expireDataSource();
                        instance.log.info("check datasource unused end..");
                        try {
                            Thread.sleep(60000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });

        }
    }

    return instance;
}

From source file:org.opendaylight.sfc.sbrest.provider.task.SbRestSfstateTaskTest.java

@Before
public void init() {
    executorService = Executors.newFixedThreadPool(10);
    PowerMockito.mockStatic(SfcProviderServiceFunctionAPI.class);
    Mockito.when(SfcProviderServiceFunctionAPI.readServiceFunction(SFSTATE_NAME))
            .thenReturn(this.buildServiceFunction());
}

From source file:com.newlandframework.avatarmq.core.AckMessageCache.java

public void parallelDispatch(LinkedList<String> list) {
    List<Callable<Long>> tasks = new ArrayList<Callable<Long>>();
    List<Future<Long>> futureList = new ArrayList<Future<Long>>();
    int startPosition = 0;
    Pair<Integer, Integer> pair = calculateBlocks(list.size(), list.size());
    int numberOfThreads = pair.getRight();
    int blocks = pair.getLeft();

    barrier = new CyclicBarrier(numberOfThreads);

    for (int i = 0; i < numberOfThreads; i++) {
        String[] task = new String[blocks];
        System.arraycopy(list.toArray(), startPosition, task, 0, blocks);
        tasks.add(new AckMessageTask(barrier, task));
        startPosition += blocks;// ww w .j  a va  2s .c o m
    }

    ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
    try {
        futureList = executor.invokeAll(tasks);
    } catch (InterruptedException ex) {
        Logger.getLogger(AckMessageCache.class.getName()).log(Level.SEVERE, null, ex);
    }

    for (Future<Long> longFuture : futureList) {
        try {
            succTaskCount += longFuture.get();
        } catch (InterruptedException ex) {
            Logger.getLogger(AckMessageCache.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ExecutionException ex) {
            Logger.getLogger(AckMessageCache.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.topekalabs.synchronization.LockTest.java

@Test
public void testWithContention() {
    final int numThreads = 4;
    ExecutorService es = Executors.newFixedThreadPool(numThreads);

    //Warmup thread pool
    testWithContentionHelper(numThreads, es);
    testWithContentionHelper(numThreads, es);

    es.shutdown();/*from w w w .  j a  va2  s. co m*/
}

From source file:com.wenyu.clustertools.ClearSnapshot.java

@Override
    public void execute() {
        ExecutorService executor = Executors.newFixedThreadPool(parallel);

        Map<Node, Future<Void>> futures = new HashMap<>();
        for (ClusterToolCmd.Node node : nodes) {
            futures.put(node, executor.submit(new Executor(node)));
        }/*from  w  w w  .j  a v  a2  s  .  co m*/

        for (Map.Entry<ClusterToolCmd.Node, Future<Void>> future : futures.entrySet()) {
            try {
                future.getValue().get(Constants.MAX_PARALLEL_WAIT_IN_SEC, TimeUnit.SECONDS);
            } catch (Exception ex) {
                System.out
                        .println(String.format("%s failed with error: %s", future.getKey().server, ex.toString()));
                ex.printStackTrace();
            }
        }
    }