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.otz.transport.consumer.dispatcher.PushNotificationDispatcher.java

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

        int dispatchersCount = Integer.parseInt(numberOfThreads);

        executorService = Executors.newFixedThreadPool(dispatchersCount);

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

    }
}

From source file:ch.windmobile.server.socialmodel.mogodb.HeavyLoadTest.java

public void testFullChatCycle() throws Exception {
    ServiceLocator locator = new MongoDBServiceLocator().connect(null);
    try {//from  w w w .  j  a  v a2  s . c om
        final int CNT = 50000;
        final Executor executor = Executors.newFixedThreadPool(10);
        final ChatService chatService = locator.getService(ChatService.class);
        final AtomicInteger counter = new AtomicInteger();
        final CountDownLatch latch = new CountDownLatch(CNT);
        for (int i = 0; i < CNT; i++) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    chatService.postMessage("TestRoom", "aUser",
                            "Hello, this is my message " + counter.incrementAndGet(), "");
                    latch.countDown();
                }
            });
        }
        System.out.println("Chat sent, waiting for the end...");
        latch.await(2, TimeUnit.MINUTES);
        Messages ret = chatService.findMessages("TEST", 5);
        System.out.println("result : " + ret);
    } finally {
        locator.disconnect();
    }
}

From source file:com.snaker.DownloadManager.java

public DownloadManager(Setting s) {
    defaultPool = Executors.newFixedThreadPool(s.getMaxConcurrentDownload());
    maxDownloadedCount = s.getMaxDownloadedCount();
    startQueueConsumeThread();
}

From source file:dk.dma.nogoservice.Application.java

@Bean
public ExecutorService slicingExecutor() {
    return Executors.newFixedThreadPool(2);
}

From source file:org.apache.mina.springrpc.example.gettingstarted.AbstractHelloServiceClientTests.java

private void executeUseConcurrent(List<Callable<HelloResponse>> tasks) {
    ExecutorService executor = Executors.newFixedThreadPool(CONCURRENT_SIZE);
    List<Future<HelloResponse>> futures = new ArrayList<Future<HelloResponse>>(RUN_TIMES);

    for (Callable<HelloResponse> task : tasks) {
        Future<HelloResponse> future = executor.submit(task);
        futures.add(future);//from  w ww . ja va 2s.  com
    }
    for (Future<HelloResponse> future : futures) {
        try {
            future.get(1000, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            continue;
        }
    }

    logger.info("Successful task count : " + counter.get());
}

From source file:de.uni_rostock.goodod.owl.OntologyCache.java

public OntologyCache(Set<? extends OWLOntologyIRIMapper> IRIMappers, Set<IRI> importsToIgnore, int threads) {
    threadCount = threads;//  w  ww .  j a  va 2s. co  m
    pendingFutures = new AtomicInteger(0);
    executor = Executors.newFixedThreadPool(threadCount);
    OWLOntologyLoaderConfiguration interimConfig = new OWLOntologyLoaderConfiguration();

    for (IRI theIRI : importsToIgnore) {
        interimConfig = interimConfig.addIgnoredImport(theIRI);
    }
    interimConfig = interimConfig.setMissingImportHandlingStrategy(MissingImportHandlingStrategy.SILENT);
    config = interimConfig;
    mappers = IRIMappers;
    futures = new HashMap<URI, FutureTask<OWLOntology>>(24);
}

From source file:org.jolokia.client.request.J4pConnectionPoolingIntegrationTest.java

private void searchParallel(J4pClient j4pClient) throws Exception {
    stubFor(get(urlPathMatching("/test/([a-z]*)"))
            .willReturn(aResponse().withFixedDelay(1000).withBody(getJsonResponse("test"))));

    final ExecutorService executorService = Executors.newFixedThreadPool(20);
    final J4pSearchRequest j4pSearchRequest = new J4pSearchRequest("java.lang:type=*");

    final List<Future<Void>> requestsList = new ArrayList<Future<Void>>();

    for (int i = 0; i < 20; i++) {
        requestsList.add(executorService.submit(new AsyncRequest(j4pClient, j4pSearchRequest)));
    }/*w  w  w  .ja  v  a2 s .co m*/

    for (Future<Void> requests : requestsList) {
        requests.get();
    }

    executorService.shutdown();
}

From source file:cherry.chart.app.LineChartBatch.java

@Override
public ExitStatus execute(String... args) {

    int nThread = (args.length < 1 ? defaultNumThread : parseInt(args[0]));
    int count = (args.length < 2 ? defaultCount : parseInt(args[1]));

    ExecutorService executorService = Executors.newFixedThreadPool(nThread);
    List<Future<Boolean>> tasks = new LinkedList<>();

    for (int i = 0; i < count; i++) {

        final String numStr = String.valueOf(i);
        tasks.add(executorService.submit(new Callable<Boolean>() {
            @Override//from   w ww.ja  v a  2  s  .  co  m
            public Boolean call() {

                File f = new File(toDir, format(file, numStr));
                String t = format(title, numStr);

                CategoryDataset dataset = createDataset();
                JFreeChart chart = ChartFactory.createLineChart(t, xLabel, yLabel, dataset);

                try (OutputStream out = new FileOutputStream(f)) {
                    ChartUtilities.writeChartAsPNG(out, chart, width, height);
                    return true;
                } catch (IOException ex) {
                    log.error("failed to create file", ex);
                    return false;
                }
            }
        }));
    }

    boolean success = true;
    for (Future<Boolean> future : tasks) {
        try {
            success &= future.get();
        } catch (ExecutionException | InterruptedException ex) {
            log.error("failed to get result", ex);
            success = false;
        }
    }
    return (success ? ExitStatus.NORMAL : ExitStatus.ERROR);
}

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

private void trySend(int numThreads, int numRepeats, int numStatements) throws Exception {
    // Create same statement X times
    EPStatement stmt[] = new EPStatement[numStatements];
    SupportMTUpdateListener listeners[] = new SupportMTUpdateListener[stmt.length];
    for (int i = 0; i < stmt.length; i++) {
        stmt[i] = engine.getEPAdministrator().createEPL(" select * " + " from "
                + SupportMarketDataBean.class.getName() + ".std:groupwin(symbol).stat:uni(price)");
        listeners[i] = new SupportMTUpdateListener();
        stmt[i].addListener(listeners[i]);
    }//from   w w  w  . j  a v  a 2  s. c  om

    // Start send threads
    // Each threads sends each symbol with price = 0 to numRepeats
    long startTime = System.currentTimeMillis();
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future future[] = new Future[numThreads];
    for (int i = 0; i < numThreads; i++) {
        Callable callable = new StmtSharedViewCallable(numRepeats, engine, SYMBOLS);
        future[i] = threadPool.submit(callable);
    }

    // Shut down
    threadPool.shutdown();
    threadPool.awaitTermination(10, TimeUnit.SECONDS);
    for (int i = 0; i < numThreads; i++) {
        assertTrue((Boolean) future[i].get());
    }
    long endTime = System.currentTimeMillis();
    long delta = endTime - startTime;
    assertTrue("delta=" + delta + " not less then 5 sec", delta < 5000); // should take less then 5 seconds even for 100 statements as they need to share resources thread-safely

    // Assert results
    for (SupportMTUpdateListener listener : listeners) {
        assertEquals(numRepeats * numThreads * SYMBOLS.length, listener.getNewDataList().size());
        EventBean[] newDataLast = listener.getNewDataList().get(listener.getNewDataList().size() - 1);
        assertEquals(1, newDataLast.length);
        EventBean result = newDataLast[0];
        assertEquals(numRepeats * numThreads, ((Long) result.get("datapoints")).longValue());
        assertTrue(Arrays.asList(SYMBOLS).contains(result.get("symbol")));
        assertEquals(sumToN(numRepeats) * numThreads, result.get("total"));
        listener.reset();
    }

    for (int i = 0; i < stmt.length; i++) {
        stmt[i].stop();
    }
}