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.sastix.cms.server.services.cache.UIDServiceTest.java

@Test
public void massiveUIDCreatorTest() throws InterruptedException {

    String region1 = "r1";
    String region2 = "r2";
    regionIdsMap.put(region1, new HashMap<>());
    regionIdsMap.put(region2, new HashMap<>());
    ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
    for (int i = 0; i < numberOfTasks; i++) {
        String region = region1;/*  w w  w.j  a  va 2  s .com*/
        if (i % 2 == 0) {
            region = region2;
        }
        Runnable worker = new UIDRunnable(region);
        executor.execute(worker);
    }

    try {
        latch.await();
    } catch (InterruptedException E) {
        // handle
    }

    executor.shutdown();
    executor.awaitTermination(5, TimeUnit.SECONDS);
    assertEquals(numberOfTasks, ids.size());
    assertEquals(numberOfTasks / 2, regionIdsMap.get(region1).size());
    assertEquals(numberOfTasks / 2, regionIdsMap.get(region2).size());
    assertTrue(!duplicateFound);
    LOG.info("Finished all threads");
}

From source file:com.alibaba.event.strategy.impl.ConcurrentTriggerStrategyImpl.java

private void initThreadPool() {
    /**  **//*w  w w  .  j a  v  a2 s. c om*/
    if (executorService != null) {
        return;
    }

    /**  **/
    executorService = Executors.newFixedThreadPool(threadPoolSize);
}

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

@Before
public void init() {
    executorService = Executors.newFixedThreadPool(10);

    PowerMockito.mockStatic(SfcProviderServiceForwarderAPI.class);
    Mockito.when(SfcProviderServiceForwarderAPI.readServiceFunctionForwarder(SFF_NAME))
            .thenReturn(this.buildServiceFunctionForwarder());
}

From source file:io.lavagna.service.ApiHooksService.java

public ApiHooksService(ProjectService projectService, CardService cardService, ApiHookQuery apiHookQuery,
        LabelService labelService, UserService userService, ConfigurationRepository configurationRepository) {
    this.projectService = projectService;
    this.cardService = cardService;
    this.apiHookQuery = apiHookQuery;
    this.labelService = labelService;
    this.userService = userService;
    this.configurationRepository = configurationRepository;
    engine = (Compilable) new ScriptEngineManager().getEngineByName("javascript");
    executor = Executors.newFixedThreadPool(4);
}

From source file:org.frontcache.include.impl.ConcurrentIncludeProcessor.java

@Override
public void init(Properties properties) {
    try {// w  ww .j  a  v a 2  s.  c om
        String threadAmountStr = properties
                .getProperty("front-cache.include-processor.impl.concurrent.thread-amount");
        if (null != threadAmountStr && threadAmountStr.trim().length() > 0)
            threadAmount = Integer.parseInt(threadAmountStr);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    logger.info("amount of threads: " + threadAmount);

    try {
        String timeoutStr = properties.getProperty("front-cache.include-processor.impl.concurrent.timeout");
        if (null != timeoutStr && timeoutStr.trim().length() > 0)
            timeout = Integer.parseInt(timeoutStr);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    logger.info("timeout: " + timeout);

    executor = Executors.newFixedThreadPool(threadAmount);
}

From source file:ai.grakn.engine.backgroundtasks.InMemoryTaskManager.java

private InMemoryTaskManager() {
    instantiatedTasks = new ConcurrentHashMap<>();
    stateStorage = InMemoryStateStorage.getInstance();
    stateUpdateLock = new ReentrantLock();

    ConfigProperties properties = ConfigProperties.getInstance();
    schedulingService = Executors.newScheduledThreadPool(1);
    executorService = Executors.newFixedThreadPool(properties.getAvailableThreads());
}

From source file:at.salzburgresearch.stanbol.enhancer.nlp.talismane.impl.TestTalismaneAnalyser.java

@BeforeClass
public static void initTalismane() throws Exception {
    executorService = Executors.newFixedThreadPool(ANALYZER_THREADS);
    analyzer = new TalismaneAnalyzer(new TalismaneStanbolConfig(AnalysedTextFactory.getDefaultInstance()),
            executorService);//from   ww w  .  j  a v a 2  s.  c  o m
    cif = InMemoryContentItemFactory.getInstance();
    //init the text eamples
    for (String name : testFileNames) {
        examples.put(name, cif.createBlob(
                new StreamSource(cl.getResourceAsStream(name), "text/plain; charset=" + UTF8.name())));
    }
}

From source file:ThreadTester.java

public void testCallable(PrintStream out) throws IOException {
    ExecutorService service = Executors.newFixedThreadPool(5);
    Future<BigInteger> prime1 = service.submit(new RandomPrimeSearch(512));
    Future<BigInteger> prime2 = service.submit(new RandomPrimeSearch(512));
    Future<BigInteger> prime3 = service.submit(new RandomPrimeSearch(512));

    try {//from ww  w.  j a v a 2  s.  com
        BigInteger bigger = (prime1.get().multiply(prime2.get())).multiply(prime3.get());
        out.println(bigger);
    } catch (InterruptedException e) {
        e.printStackTrace(out);
    } catch (ExecutionException e) {
        e.printStackTrace(out);
    }
}

From source file:com.espertech.esper.multithread.TestMTDeterminismListener.java

private void trySend(int numThreads, int numEvents, boolean isPreserveOrder,
        ConfigurationEngineDefaults.Threading.Locking locking) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    config.getEngineDefaults().getThreading().setListenerDispatchPreserveOrder(isPreserveOrder);
    config.getEngineDefaults().getThreading().setListenerDispatchLocking(locking);

    engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();/*w ww . j  a  v  a2  s . co  m*/

    // setup statements
    EPStatement stmtInsert = engine.getEPAdministrator()
            .createEPL("select count(*) as cnt from " + SupportBean.class.getName());
    SupportMTUpdateListener listener = new SupportMTUpdateListener();
    stmtInsert.addListener(listener);

    // execute
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future future[] = new Future[numThreads];
    for (int i = 0; i < numThreads; i++) {
        future[i] = threadPool.submit(new SendEventCallable(i, engine, new GeneratorIterator(numEvents)));
    }

    threadPool.shutdown();
    threadPool.awaitTermination(10, TimeUnit.SECONDS);

    for (int i = 0; i < numThreads; i++) {
        assertTrue((Boolean) future[i].get());
    }

    EventBean events[] = listener.getNewDataListFlattened();
    long[] result = new long[events.length];
    for (int i = 0; i < events.length; i++) {
        result[i] = (Long) events[i].get("cnt");
    }
    //log.info(".trySend result=" + Arrays.toString(result));

    // assert result
    assertEquals(numEvents * numThreads, events.length);
    for (int i = 0; i < numEvents * numThreads; i++) {
        assertEquals(result[i], (long) i + 1);
    }
}

From source file:com.uber.hoodie.common.util.queue.BoundedInMemoryExecutor.java

public BoundedInMemoryExecutor(final long bufferLimitInBytes, List<BoundedInMemoryQueueProducer<I>> producers,
        Optional<BoundedInMemoryQueueConsumer<O, E>> consumer, final Function<I, O> transformFunction,
        final SizeEstimator<O> sizeEstimator) {
    this.producers = producers;
    this.consumer = consumer;
    // Ensure single thread for each producer thread and one for consumer
    this.executorService = Executors.newFixedThreadPool(producers.size() + 1);
    this.queue = new BoundedInMemoryQueue<>(bufferLimitInBytes, transformFunction, sizeEstimator);
}