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:com.alibaba.dubbo.demo.consumer.DemoAction.java

public void start() throws Exception {
    int threads = 100;

    final DescriptiveStatistics stats = new SynchronizedDescriptiveStatistics();

    DubboBenchmark.BenchmarkMessage msg = prepareArgs();
    final byte[] msgBytes = msg.toByteArray();

    int n = 1000000;
    final CountDownLatch latch = new CountDownLatch(n);

    ExecutorService es = Executors.newFixedThreadPool(threads);

    final AtomicInteger trans = new AtomicInteger(0);
    final AtomicInteger transOK = new AtomicInteger(0);

    long start = System.currentTimeMillis();
    for (int i = 0; i < n; i++) {
        es.submit(() -> {
            try {

                long t = System.currentTimeMillis();
                DubboBenchmark.BenchmarkMessage m = testSay(msgBytes);
                t = System.currentTimeMillis() - t;
                stats.addValue(t);//from ww  w. j  ava  2 s  .co  m

                trans.incrementAndGet();

                if (m != null && m.getField1().equals("OK")) {
                    transOK.incrementAndGet();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        });
    }

    latch.await();

    start = System.currentTimeMillis() - start;

    System.out.printf("sent     requests    : %d\n", n);
    System.out.printf("received requests    : %d\n", trans.get());
    System.out.printf("received requests_OK : %d\n", transOK.get());
    System.out.printf("throughput  (TPS)    : %d\n", n * 1000 / start);

    System.out.printf("mean: %f\n", stats.getMean());
    System.out.printf("median: %f\n", stats.getPercentile(50));
    System.out.printf("max: %f\n", stats.getMax());
    System.out.printf("min: %f\n", stats.getMin());

    System.out.printf("99P: %f\n", stats.getPercentile(90));
}

From source file:io.specto.hoverfly.junit.core.Hoverfly.java

private void cleanUp() {
    LOGGER.info("Destroying hoverfly process");

    if (startedProcess != null) {
        Process process = startedProcess.getProcess();
        process.destroy();/*from   w  w w.j a v  a 2  s.  c o m*/

        // Some platforms terminate process asynchronously, eg. Windows, and cannot guarantee that synchronous file deletion
        // can acquire file lock
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<Integer> future = executorService.submit((Callable<Integer>) process::waitFor);
        try {
            future.get(5, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            LOGGER.warn("Timeout when waiting for hoverfly process to terminate.");
        }
        executorService.shutdownNow();
    }

    proxyConfigurer.restoreProxySystemProperties();
    // TODO: reset default SslContext?
    tempFileManager.purge();
}

From source file:com.netflix.curator.framework.recipes.locks.TestInterProcessReadWriteLock.java

@Test
public void testThatDowngradingRespectsThreads() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {/*  www  .  j  a  v  a  2 s  .co m*/
        client.start();

        final InterProcessReadWriteLock lock = new InterProcessReadWriteLock(client, "/lock");
        ExecutorService t1 = Executors.newSingleThreadExecutor();
        ExecutorService t2 = Executors.newSingleThreadExecutor();

        final CountDownLatch latch = new CountDownLatch(1);

        Future<Object> f1 = t1.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                lock.writeLock().acquire();
                latch.countDown();
                return null;
            }
        });

        Future<Object> f2 = t2.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Assert.assertTrue(latch.await(10, TimeUnit.SECONDS));
                Assert.assertFalse(lock.readLock().acquire(5, TimeUnit.SECONDS));
                return null;
            }
        });

        f1.get();
        f2.get();
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.palantir.atlasdb.schema.stream.StreamTest.java

private void runConflictingTasksConcurrently(long streamId, TwoConflictingTasks twoConflictingTasks)
        throws InterruptedException {
    final CountDownLatch firstLatch = new CountDownLatch(1);
    final CountDownLatch secondLatch = new CountDownLatch(1);

    ExecutorService exec = PTExecutors.newFixedThreadPool(2);

    Future<?> firstFuture = exec.submit(() -> {
        try {/*from   w  w w.  ja v  a 2  s .  c om*/
            txManager.runTaskThrowOnConflict(t -> {
                twoConflictingTasks.startFirstAndFail(t, streamId);
                letOtherTaskFinish(firstLatch, secondLatch);
                return null;
            });
            fail("Because we concurrently wrote, we should have failed with TransactionConflictException.");
        } catch (TransactionConflictException e) {
            // expected
        }
    });

    firstLatch.await();

    Future<?> secondFuture = exec.submit(
            (Runnable) () -> txManager.runTaskThrowOnConflict((TransactionTask<Void, RuntimeException>) t -> {
                twoConflictingTasks.startSecondAndFinish(t, streamId);
                return null;
            }));

    exec.shutdown();
    Futures.getUnchecked(secondFuture);

    secondLatch.countDown();
    Futures.getUnchecked(firstFuture);
}

From source file:jenkins.plugins.office365connector.HttpWorkerTest.java

@Test
public void testSendingMultipleWebhooks() throws IOException, InterruptedException {
    ExecutorService executorService = Executors.newCachedThreadPool();
    HttpWorker worker1 = new HttpWorker("http://localhost:8000/test1", "test1body", 30000,
            Mockito.mock(PrintStream.class));
    HttpWorker worker2 = new HttpWorker("http://localhost:8000/test2", "test2body", 30000,
            Mockito.mock(PrintStream.class));
    executorService.submit(worker1);
    executorService.submit(worker2);//from   w w  w  .  j av a2 s. c  om
    executorService.shutdown();
    executorService.awaitTermination(5, TimeUnit.SECONDS);
    Assert.assertTrue(MyHandler.getTest1Result());
    Assert.assertTrue(MyHandler.getTest2Result());
}

From source file:io.syndesis.project.converter.DefaultProjectGenerator.java

private InputStream createTarInputStream(GenerateProjectRequest request) throws IOException {
    PipedInputStream is = new PipedInputStream();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    PipedOutputStream os = new PipedOutputStream(is);
    executor.submit(generateAddProjectTarEntries(request, os));

    return is;//w w w  .  j ava  2s  .c o  m
}

From source file:main.ScorePipeline.java

/**
 * This method calculates similarities bin-based between yeast_human spectra
 * on the first data set against all yeast spectra on the second data set
 *
 * @param min_mz//from www. j a v  a 2s  .  c  om
 * @param max_mz
 * @param topN
 * @param percentage
 * @param yeast_and_human_file
 * @param is_precursor_peak_removal
 * @param fragment_tolerance
 * @param noiseFiltering
 * @param transformation
 * @param intensities_sum_or_mean_or_median
 * @param yeast_spectra
 * @param bw
 * @param charge
 * @param charge_situation
 * @throws IllegalArgumentException
 * @throws ClassNotFoundException
 * @throws IOException
 * @throws MzMLUnmarshallerException
 * @throws NumberFormatException
 * @throws ExecutionException
 * @throws InterruptedException
 */
private static void calculate_BinBasedScoresObsolete_AllTogether(ArrayList<BinMSnSpectrum> yeast_spectra,
        ArrayList<BinMSnSpectrum> yeast_human_spectra, BufferedWriter bw, int charge, double precursorTol,
        double fragTol) throws IllegalArgumentException, ClassNotFoundException, IOException,
        MzMLUnmarshallerException, NumberFormatException, InterruptedException {
    ExecutorService excService = Executors
            .newFixedThreadPool(ConfigHolder.getInstance().getInt("thread.numbers"));
    List<Future<SimilarityResult>> futureList = new ArrayList<>();
    for (BinMSnSpectrum binYeastHumanSp : yeast_human_spectra) {
        int tmpMSCharge = binYeastHumanSp.getSpectrum().getPrecursor().getPossibleCharges().get(0).value;
        if (charge == 0 || tmpMSCharge == charge) {
            if (!binYeastHumanSp.getSpectrum().getPeakList().isEmpty() && !yeast_spectra.isEmpty()) {
                Calculate_Similarity similarity = new Calculate_Similarity(binYeastHumanSp, yeast_spectra,
                        fragTol, precursorTol);
                Future future = excService.submit(similarity);
                futureList.add(future);
            }
        }
    }
    for (Future<SimilarityResult> future : futureList) {
        try {
            SimilarityResult get = future.get();
            String tmp_charge = get.getSpectrumChargeAsString(), spectrum = get.getSpectrumName();
            double tmpPrecMZ = get.getSpectrumPrecursorMZ();
            double dot_product = get.getScores().get(SimilarityMethods.NORMALIZED_DOT_PRODUCT_STANDARD),
                    dot_product_skolow = get.getScores().get(SimilarityMethods.NORMALIZED_DOT_PRODUCT_SOKOLOW),
                    pearson = get.getScores().get(SimilarityMethods.PEARSONS_CORRELATION),
                    spearman = get.getScores().get(SimilarityMethods.SPEARMANS_CORRELATION);
            if (dot_product == Double.MIN_VALUE) {
                LOGGER.info("The similarity for the spectrum " + spectrum
                        + " is too small to keep the record, therefore score is not computed.");
                // Means that score has not been calculated!
                //                    bw.write(tmp_Name + "\t" + tmp_charge + "\t" + tmpPrecMZ + "\t");
                //                    bw.write("NA" + "\t" + "NA" + "\t" + "NA" + "\t" + "NA");
            } else {
                bw.write(spectrum + "\t" + tmp_charge + "\t" + tmpPrecMZ + "\t" + get.getSpectrumToCompare()
                        + "\t");
                bw.write(dot_product + "\t" + dot_product_skolow + "\t" + pearson + "\t" + spearman + "\n");
            }
        } catch (InterruptedException | ExecutionException e) {
            LOGGER.error(e);
        }
    }
}

From source file:be.vlaanderen.sesam.monitor.internal.util.ThreadPoolTaskScheduler.java

public <T> Future<T> submit(Callable<T> task) {
    ExecutorService executor = getScheduledExecutor();
    try {/*w  ww. j  a va  2  s  .c  o m*/
        if (this.errorHandler != null) {
            task = new DelegatingErrorHandlingCallable<T>(task, this.errorHandler);
        }
        return executor.submit(task);
    } catch (RejectedExecutionException ex) {
        throw new TaskRejectedException("Executor [" + executor + "] did not accept task: " + task, ex);
    }
}

From source file:main.ScorePipeline.java

/**
 * This method calculates similarities bin-based between yeast_human spectra
 * on the first data set against all yeast spectra on the second data set
 *
 * @param min_mz//from   w ww  . j ava  2  s.com
 * @param max_mz
 * @param topN
 * @param percentage
 * @param yeast_and_human_file
 * @param is_precursor_peak_removal
 * @param fragment_tolerance
 * @param noiseFiltering
 * @param transformation
 * @param intensities_sum_or_mean_or_median
 * @param yeast_spectra
 * @param bw
 * @param charge
 * @param charge_situation
 * @throws IllegalArgumentException
 * @throws ClassNotFoundException
 * @throws IOException
 * @throws MzMLUnmarshallerException
 * @throws NumberFormatException
 * @throws ExecutionException
 * @throws InterruptedException
 */
private static void calculate_BinBasedScores(ArrayList<BinMSnSpectrum> yeast_spectra,
        ArrayList<BinMSnSpectrum> yeast_human_spectra, BufferedWriter bw, int charge, double precursorTol,
        double fragTol, String scoreType) throws IllegalArgumentException, ClassNotFoundException, IOException,
        MzMLUnmarshallerException, NumberFormatException, InterruptedException {
    ExecutorService excService = Executors
            .newFixedThreadPool(ConfigHolder.getInstance().getInt("thread.numbers"));
    List<Future<SimilarityResult>> futureList = new ArrayList<>();
    for (BinMSnSpectrum binYeastHumanSp : yeast_human_spectra) {
        int tmpMSCharge = binYeastHumanSp.getSpectrum().getPrecursor().getPossibleCharges().get(0).value;
        if (charge == 0 || tmpMSCharge == charge) {
            if (!binYeastHumanSp.getSpectrum().getPeakList().isEmpty() && !yeast_spectra.isEmpty()) {
                Calculate_Similarity similarity = new Calculate_Similarity(binYeastHumanSp, yeast_spectra,
                        fragTol, precursorTol);
                Future future = excService.submit(similarity);
                futureList.add(future);
            }
        }
    }
    SimilarityMethods method = SimilarityMethods.NORMALIZED_DOT_PRODUCT_STANDARD;
    if (scoreType.equals("spearman")) {
        method = SimilarityMethods.SPEARMANS_CORRELATION;
    } else if (scoreType.equals("pearson")) {
        method = SimilarityMethods.PEARSONS_CORRELATION;
    }
    for (Future<SimilarityResult> future : futureList) {
        try {
            SimilarityResult get = future.get();
            String tmp_charge = get.getSpectrumChargeAsString(), spectrum = get.getSpectrumName();
            double tmpPrecMZ = get.getSpectrumPrecursorMZ(), score = get.getScores().get(method);
            if (score == Double.MIN_VALUE) {
                LOGGER.info("The similarity for the spectrum " + spectrum
                        + " is too small to keep the record, therefore score is not computed.");
                // Means that score has not been calculated!
                //                    bw.write(tmp_Name + "\t" + tmp_charge + "\t" + tmpPrecMZ + "\t");
                //                    bw.write("NA" + "\t" + "NA" + "\t" + "NA" + "\t" + "NA");
            } else {
                bw.write(spectrum + "\t" + tmp_charge + "\t" + tmpPrecMZ + "\t" + get.getSpectrumToCompare()
                        + "\t" + score + "\n");
            }
        } catch (InterruptedException | ExecutionException e) {
            LOGGER.error(e);
        }
    }
}

From source file:com.netflix.config.ConcurrentMapConfigurationTest.java

@Test
public void testConcurrency() {
    final ConcurrentMapConfiguration conf = new ConcurrentMapConfiguration();
    ExecutorService exectuor = Executors.newFixedThreadPool(20);
    final CountDownLatch doneSignal = new CountDownLatch(1000);
    for (int i = 0; i < 1000; i++) {
        final Integer index = i;
        exectuor.submit(new Runnable() {
            public void run() {
                conf.addProperty("key", index);
                conf.addProperty("key", "stringValue");
                doneSignal.countDown();/*from w  w  w . j  av  a  2  s  .  c om*/
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                }
            }
        });
    }
    try {
        doneSignal.await();
    } catch (InterruptedException e) {

    }
    List prop = (List) conf.getProperty("key");
    assertEquals(2000, prop.size());
}