Example usage for java.util.concurrent ExecutorService submit

List of usage examples for java.util.concurrent ExecutorService submit

Introduction

In this page you can find the example usage for java.util.concurrent ExecutorService submit.

Prototype

Future<?> submit(Runnable task);

Source Link

Document

Submits a Runnable task for execution and returns a Future representing that task.

Usage

From source file:org.auraframework.integration.test.http.AuraResourceServletLoggingHttpTest.java

/**
 * test add for W-2792895//from   ww w .  j  av  a  2s.  co m
   also since I ask cache to log something when hit miss, this kind of verify W-2105858 as well
 */
@Test
public void testConcurrentGetRequests() throws Exception {
    // I tried to use obtainGetMethod(url) then perform(HttpGet) , but
    // our default httpClient use BasicClientConnectionManager, which doesn't work well with MultiThread
    // let's use PoolingHttpClientConnectionManager instead.
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    // Increase max total connection to 200 -- just some big number
    cm.setMaxTotal(200);
    // Increase default max connection per route to 20 -- again, just some big numer
    cm.setDefaultMaxPerRoute(20);
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

    String modeAndContext = getSimpleContext(Format.JS, false);
    String url = "/l/" + AuraTextUtil.urlencode(modeAndContext) + "/app.js";

    int numOfRequest = 5;
    List<Request> requests = new ArrayList<>();
    for (int i = 1; i <= numOfRequest; i++) {
        requests.add(new Request(httpClient, url));
    }

    ExecutorService excutor = Executors.newFixedThreadPool(numOfRequest);
    List<Future<Integer>> responses = new ArrayList<>();
    for (Request request : requests) {
        responses.add(excutor.submit(request));
    }
    for (Future<Integer> response : responses) {
        response.get();
    }

    int counter = 0;
    String message;
    List<LoggingEvent> logs = appender.getLog();
    for (LoggingEvent le : logs) {
        message = le.getMessage().toString();
        if (message.contains("StringsCache")) {
            counter++;
            assertTrue("get unexpected logging message for cache miss:" + message,
                    message.contains("cache miss for key: JS:DEV:"));
        }
    }
    //run this test right after server is up, we get one miss. second time, what we looking for is cached already, no miss.
    assertTrue("we should only have no more than one cache miss, instead we have " + counter, counter <= 1);
}

From source file:org.neo4j.ogm.integration.TransactionRequestHandlerTest.java

@Test
public void shouldBeAbleToStartMultipleConcurrentLongRunningTransactions() throws InterruptedException {

    SessionFactory sessionFactory = new SessionFactory();
    session = sessionFactory.openSession(neo4jRule.url());

    int numThreads = 100;

    ExecutorService executor = Executors.newFixedThreadPool(numThreads);
    CountDownLatch latch = new CountDownLatch(numThreads);

    for (int i = 0; i < numThreads; i++) {
        executor.submit(new TransactionStarter(latch));
    }/*  w w w .  ja  va  2  s . c  om*/
    latch.await(); // pause until the count reaches 0
    System.out.println("all threads running");
    executor.shutdownNow();
}

From source file:com.scaleoutsoftware.soss.hserver.hadoop.SubmittedJob.java

public void submit() {
    ExecutorService async = Executors.newSingleThreadExecutor();
    runningJob = async.submit(this);
    async.shutdown();/*from w w w .j av  a 2 s . c o m*/
}

From source file:io.wcm.caravan.pipeline.impl.JsonPipelineMultipleSubscriptionsTest.java

@Test
public void subscribeConcurrentlyToTransformedPipelineOutputs() throws InterruptedException {

    // this test verifies that pipelines actions are only executed once, even if there are multiple concurrent subscribers
    firstStep = newPipelineWithResponseBody("{id:123}");
    secondStep = firstStep.applyAction(action);
    when(action.execute(any(), any())).thenReturn(firstStep.getOutput());

    // create multiple simultaneous threads that subscribe to the same pipeline output
    // and use a CountDownLatch to delay the subscription until all threads have been started
    CountDownLatch countDown = new CountDownLatch(100);
    ExecutorService executorService = Executors.newCachedThreadPool();
    while (countDown.getCount() > 0) {

        executorService.submit(() -> {

            countDown.await();/* ww  w.  j  a v a  2 s  .c  om*/
            secondStep.getOutput().subscribe(Subscribers.empty());

            return null; // this is required for the lambda to be considered a Callable<Void> and therefore be allowed to throw exceptions
        });

        countDown.countDown();
    }

    executorService.shutdown();
    executorService.awaitTermination(1, TimeUnit.MINUTES);

    verify(action, times(1)).execute(any(), any());
}

From source file:edu.cmu.lti.oaqa.bioqa.providers.kb.TmToolConceptProvider.java

@Override
public List<Concept> getConcepts(List<JCas> jcases) throws AnalysisEngineProcessException {
    // send request
    List<String> normalizedTexts = jcases.stream().map(JCas::getDocumentText)
            .map(PubAnnotationConvertUtil::normalizeText).collect(toList());
    ListMultimap<Integer, PubAnnotation.Denotation> index2denotations = Multimaps
            .synchronizedListMultimap(ArrayListMultimap.create());
    ExecutorService es = Executors.newCachedThreadPool();
    for (String trigger : triggers) {
        es.submit(() -> {
            try {
                List<String> denotationStrings = requestConcepts(normalizedTexts, trigger);
                assert denotationStrings.size() == jcases.size();
                for (int i = 0; i < jcases.size(); i++) {
                    PubAnnotation.Denotation[] denotations = gson.fromJson(denotationStrings.get(i),
                            PubAnnotation.Denotation[].class);
                    index2denotations.putAll(i, Arrays.asList(denotations));
                }//from  www.  ja va  2 s . co m
            } catch (Exception e) {
                throw TmToolConceptProviderException.unknownException(trigger, e);
            }
        });
    }
    es.shutdown();
    try {
        boolean status = es.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        if (!status) {
            throw new AnalysisEngineProcessException();
        }
    } catch (InterruptedException e) {
        throw new AnalysisEngineProcessException(e);
    }
    // convert denotation strings
    List<Concept> concepts = new ArrayList<>();
    for (int i = 0; i < jcases.size(); i++) {
        JCas jcas = jcases.get(i);
        List<PubAnnotation.Denotation> denotations = index2denotations.get(i);
        try {
            concepts.addAll(PubAnnotationConvertUtil.convertDenotationsToConcepts(jcas, denotations));
        } catch (StringIndexOutOfBoundsException e) {
            throw TmToolConceptProviderException.offsetOutOfBounds(jcas.getDocumentText(), denotations, e);
        }
    }
    return concepts;
}

From source file:io.github.mmichaelis.selenium.client.provider.AbstractWebDriverProviderTest.java

private void prepareResetTest(final HtmlUnitDriver testedDriver)
        throws InterruptedException, ExecutionException {
    final URL otherPageUrl = Resources.getResource(this.getClass(), "page2.html");
    final URL newPageUrl = Resources.getResource(this.getClass(), "page3.html");
    final WebDriverProvider driverProvider = new NoExceptionWebDriverProvider(testedDriver);
    final ExecutorService executorService = newCachedThreadPool();
    final Future<Void> openWindowResultFuture = executorService.submit(new Callable<Void>() {
        @Nullable/*from   www  .j  a  v a 2 s . c  o  m*/
        @Override
        public Void call() {
            final WebDriver driver = driverProvider.get();
            driver.get(otherPageUrl.toExternalForm());
            final JavascriptExecutor executor = (JavascriptExecutor) driver;
            executor.executeScript("window.open(arguments[0])", newPageUrl.toExternalForm());
            final Set<String> windowHandles = driver.getWindowHandles();
            checkState(windowHandles.size() > 1, "Failed to open additional window for driver: %s", driver);
            driverProvider.reset();
            return null;
        }
    });
    openWindowResultFuture.get();
}

From source file:com.amazonaws.services.kinesis.producer.KinesisProducerTest.java

@Test
public void multipleInstances() throws Exception {
    int N = 8;//from w w w . j a v  a  2 s.  com
    final KinesisProducer[] kps = new KinesisProducer[N];
    ExecutorService exec = Executors.newFixedThreadPool(N);
    for (int i = 0; i < N; i++) {
        final int n = i;
        exec.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    kps[n] = getProducer(null, null);
                } catch (Exception e) {
                    log.error("Error starting KPL", e);
                }
            }
        });
    }
    exec.shutdown();
    exec.awaitTermination(30, TimeUnit.SECONDS);
    Thread.sleep(10000);
    for (int i = 0; i < N; i++) {
        assertNotNull(kps[i]);
        assertNotNull(kps[i].getMetrics());
        kps[i].destroy();
    }
}

From source file:com.opengamma.bbg.replay.BloombergTickWriterTest.java

@Test(invocationCount = 5, successPercentage = 19)
public void performance() throws Exception {
    ExecutorService writerExecutor = Executors.newSingleThreadExecutor();
    Future<?> writerFuture = writerExecutor.submit(_writer);

    double nStartTime = System.currentTimeMillis();

    //create ticks generators
    List<RandomTicksGeneratorJob> ticksGeneratorsList = new ArrayList<RandomTicksGeneratorJob>();
    List<Thread> ticksGeneratorThreads = new ArrayList<Thread>();
    for (int i = 0; i < TICKS_GENERATOR_THREAD_SIZE; i++) {
        RandomTicksGeneratorJob ticksGeneratorJob = new RandomTicksGeneratorJob(
                new ArrayList<String>(_ticker2buid.keySet()), _allTicksQueue);
        ticksGeneratorsList.add(ticksGeneratorJob);
        Thread thread = new Thread(ticksGeneratorJob, "TicksGenerator" + i);
        thread.start();/*from w  w  w  .j  a v a 2  s.co m*/
        ticksGeneratorThreads.add(thread);
    }

    s_logger.info("Test running for 1min to gather stats");
    Thread.sleep(RUN_DURATION);

    for (RandomTicksGeneratorJob ticksGeneratorJob : ticksGeneratorsList) {
        ticksGeneratorJob.terminate();
    }

    //wait for all ticksGenerator threads to finish
    for (Thread thread : ticksGeneratorThreads) {
        thread.join();
    }

    //send terminate message for tickWriter to terminate
    sendTerminateMessage();

    //test should fail if writer throws an exception
    writerFuture.get();
    writerExecutor.shutdown();
    writerExecutor.awaitTermination(1, TimeUnit.SECONDS);

    double nRunDuration = System.currentTimeMillis() - nStartTime;

    double nTicks = ((double) _writer.getNTicks() / nRunDuration) * 1000;
    s_logger.info("ticks {}/s", nTicks);
    double nWrites = ((double) _writer.getNWrites() / nRunDuration) * 1000;
    s_logger.info("fileOperations {}/s", nWrites);
    double nBlocks = (double) _writer.getNBlocks() / (double) _writer.getNWrites();
    s_logger.info("average blocks {}bytes", nBlocks);

    assertTrue("reportInterval > testRunTime", REPORT_INTERVAL > nRunDuration);
    if ((nWrites * nBlocks) < WRITER_SPEED_THRESHOLD) {
        s_logger.warn("BloombergTickWriter looks like running really slower than {}b/s",
                WRITER_SPEED_THRESHOLD);
    }
}

From source file:me.carpela.network.pt.cracker.tools.ttorrent.Torrent.java

private static String hashFiles(List<File> files, int pieceLenght)
        throws InterruptedException, IOException, NoSuchAlgorithmException {
    int threads = getHashingThreadsCount();
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    ByteBuffer buffer = ByteBuffer.allocate(pieceLenght);
    List<Future<String>> results = new LinkedList<Future<String>>();
    StringBuilder hashes = new StringBuilder();

    long length = 0L;
    int pieces = 0;

    long start = System.nanoTime();
    for (File file : files) {

        length += file.length();/*from  ww w. j a  v a 2 s  .com*/

        FileInputStream fis = new FileInputStream(file);
        FileChannel channel = fis.getChannel();
        int step = 10;

        try {
            while (channel.read(buffer) > 0) {
                if (buffer.remaining() == 0) {
                    buffer.clear();
                    results.add(executor.submit(new CallableChunkHasher(buffer)));
                }

                if (results.size() >= threads) {
                    pieces += accumulateHashes(hashes, results);
                }

                if (channel.position() / (double) channel.size() * 100f > step) {
                    step += 10;
                }
            }
        } finally {
            channel.close();
            fis.close();
        }
    }

    // Hash the last bit, if any
    if (buffer.position() > 0) {
        buffer.limit(buffer.position());
        buffer.position(0);
        results.add(executor.submit(new CallableChunkHasher(buffer)));
    }

    pieces += accumulateHashes(hashes, results);

    // Request orderly executor shutdown and wait for hashing tasks to
    // complete.
    executor.shutdown();
    while (!executor.isTerminated()) {
        Thread.sleep(10);
    }
    long elapsed = System.nanoTime() - start;

    int expectedPieces = (int) (Math.ceil((double) length / pieceLenght));
    return hashes.toString();
}

From source file:com.kurento.kmf.test.base.GridBrowserMediaApiTest.java

public void runParallel(Runnable myFunc) throws InterruptedException, ExecutionException {
    ExecutorService exec = Executors.newFixedThreadPool(1);
    exec.submit(myFunc).get();
}