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:main.ScorePipeline.java

/**
 *
 * This method calculates similarities for MSRobin for each spectra on
 * yeast_human_spectra on the first data set against all yeast spectra on
 * the second data set/*from  w w w  . j av a 2s .  c om*/
 *
 * thydMSnSpectra-yeast-human, tsolMSnSpectra-yeast,
 *
 * @param tsolMSnSpectra
 * @param thydMSnSpectra
 * @param bw
 * @param fragTol
 * @param precTol
 * @throws IllegalArgumentException
 * @throws ClassNotFoundException
 * @throws IOException
 * @throws MzMLUnmarshallerException
 * @throws NumberFormatException
 * @throws InterruptedException
 */
private static void calculate_MSRobins(ArrayList<MSnSpectrum> tsolMSnSpectra,
        ArrayList<MSnSpectrum> thydMSnSpectra, BufferedWriter bw, double fragTol, double precTol,
        int calculationOptionIntensityMSRobin, int msRobinCalculationOption)
        throws IllegalArgumentException, ClassNotFoundException, IOException, MzMLUnmarshallerException,
        NumberFormatException, InterruptedException {
    ExecutorService excService = Executors
            .newFixedThreadPool(ConfigHolder.getInstance().getInt("thread.numbers"));
    List<Future<SimilarityResult>> futureList = new ArrayList<>();
    for (MSnSpectrum thydMSnSpectrum : thydMSnSpectra) {
        Calculate_Similarity similarity = new Calculate_Similarity(thydMSnSpectrum, tsolMSnSpectra, fragTol,
                precTol, calculationOptionIntensityMSRobin, msRobinCalculationOption);
        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 tmp_precursor_mz = get.getSpectrumPrecursorMZ(),
                    msrobin = get.getScores().get(SimilarityMethods.MSRobin);
            if (msrobin == 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" + "\n");
            } else {
                bw.write(spectrum + "\t" + tmp_charge + "\t" + tmp_precursor_mz + "\t"
                        + get.getSpectrumToCompare() + "\t" + msrobin + "\n");
            }
        } catch (InterruptedException | ExecutionException e) {
            LOGGER.error(e);
        }
    }
    excService.shutdown();

}

From source file:es.upv.grycap.coreutils.fiber.test.FetchCancellationTest.java

@Test
public void testFetch() throws Exception {
    // create fetcher
    final HttpDataFetcher fetcher = new HttpDataFetcher(2);
    assertThat("Fetcher was created", fetcher, notNullValue());

    // create output folder
    final File outDir = tmpFolder.newFolder(randomAlphanumeric(12));
    assertThat("Output dir was created", outDir, notNullValue());
    assertThat("Output dir is writable", outDir.canWrite());

    // submit request and cancel
    final ExecutorService executorService = Executors.newFixedThreadPool(2);
    final Future<Map<String, FetchStatus>> future = executorService
            .submit(new Callable<Map<String, FetchStatus>>() {
                @Override//from  w  w  w .j a v  a  2  s . c o  m
                public Map<String, FetchStatus> call() throws Exception {
                    return AsyncCompletionStage
                            .get(fetcher.fetchToDir(new URL(MOCK_SERVER_BASE_URL + "/fetch/long-waiting"),
                                    ImmutableList.of("1"), outDir), 120000l, TimeUnit.SECONDS);
                }
            });
    assertThat("Request was cancelled", future.cancel(true));
    assertThat("File does not exist", not(new File(outDir, "1").exists()));
}

From source file:com.mirth.connect.connectors.ws.WebServiceConnectorService.java

private Future<WsdlInterface> importWsdlInterface(final WsdlProject wsdlProject, final URI newWsdlUrl,
        final WsdlLoader wsdlLoader) {
    ExecutorService executor = Executors.newSingleThreadExecutor();

    return executor.submit(new Callable<WsdlInterface>() {
        public WsdlInterface call() throws Exception {
            WsdlInterface[] wsdlInterfaces = WsdlInterfaceFactory.importWsdl(wsdlProject,
                    newWsdlUrl.toURL().toString(), false, wsdlLoader);
            return wsdlInterfaces[0];
        }/*w ww  .  j  a v  a2 s. c  o  m*/
    });
}

From source file:net.openhft.chronicle.logger.VanillChronicleQueuePerfTest.java

@Test
public void testMultiThreadLogging() throws IOException, InterruptedException {

    final int RUNS = 15000000;
    final int THREADS = Runtime.getRuntime().availableProcessors();

    for (int size : new int[] { 64, 128, 256 }) {
        {//from www.  ja va  2s  . c om
            final long start = System.nanoTime();

            ExecutorService es = Executors.newFixedThreadPool(THREADS);
            for (int t = 0; t < THREADS; t++) {
                es.submit(new RunnableLogger(RUNS, size));
            }

            es.shutdown();
            es.awaitTermination(2, TimeUnit.MINUTES);

            final long time = System.nanoTime() - start;

            System.out.printf(
                    "ChronicleLog.MT (runs=%d, min size=%03d, elapsed=%.3f ms) took an average of %.3f us per entry\n",
                    RUNS, size, time / 1e6, time / 1e3 / (RUNS * THREADS));
        }
    }
}

From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedBarrier.java

@Test
public void testBasic() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {// w w  w  .  ja va  2 s.c  o  m
        client.start();

        final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier");
        barrier.setBarrier();

        ExecutorService service = Executors.newSingleThreadExecutor();
        service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Thread.sleep(1000);
                barrier.removeBarrier();
                return null;
            }
        });

        Assert.assertTrue(barrier.waitOnBarrier(10, TimeUnit.SECONDS));
    } finally {
        client.close();
    }
}

From source file:eu.cloudscale.showcase.servlets.helpers.PaymentService.java

@Async
public Future<String> callPaymentService(String distribution, String attr1, String attr2, String attr3) {
    try {/* w  w  w. j  a  va 2  s  .c  o m*/
        ExecutorService executor = Executors.newFixedThreadPool(1);
        String url = this.getUrl(distribution, attr1, attr2, attr3);
        Future<Response> response = executor.submit(new Request(new URL(url)));
        InputStream input = response.get().getBody();
        executor.shutdown();

        String body = IOUtils.toString(input, "UTF-8");
        return new AsyncResult<String>(body);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.brienwheeler.lib.concurrent.ExecutorsTest.java

@Test
public void testNewSingleThreadExecutorShutdownNow() throws InterruptedException {
    NamedThreadFactory threadFactory = new NamedThreadFactory(THREAD_FACTORY_NAME);
    ExecutorService executor = Executors.newSingleThreadExecutor(threadFactory);

    executor.submit(new SleepRunnable(10L));
    Future<?> notExecutedRunnable = executor.submit(new NullRunnable());
    Future<?> notExecutedCallable = executor.submit(new NullCallable());
    Future<Integer> notEexecutedRunnable2 = executor.submit(new NullRunnable(), 1);

    List<Runnable> notExecuted = executor.shutdownNow();
    Assert.assertTrue(executor.isShutdown());
    Assert.assertEquals(3, notExecuted.size());
    Assert.assertTrue(CollectionUtils.containsInstance(notExecuted, notExecutedRunnable));
    Assert.assertTrue(CollectionUtils.containsInstance(notExecuted, notExecutedCallable));
    Assert.assertTrue(CollectionUtils.containsInstance(notExecuted, notEexecutedRunnable2));

    executor.awaitTermination(10, TimeUnit.MILLISECONDS);
    Assert.assertTrue(executor.isTerminated());
}

From source file:com.github.viktornar.controller.composer.ComposeController.java

private void runPrintTask(ExecutorService executorService, Atlas atlas, Repository repository,
        SettingsService settingsService) {
    executorService.submit(new PrintTask(executorService, atlas, repository, settingsService));
}

From source file:com.norconex.committer.AbstractFileQueueCommitterTest.java

@Test
public void testMultipleCommitThread() throws Exception {

    final AtomicInteger counter = new AtomicInteger();

    final AbstractFileQueueCommitter committer = new AbstractFileQueueCommitter() {

        @Override// w w w. j  av a 2  s . co m
        protected void commitAddition(IAddOperation operation) throws IOException {
            counter.incrementAndGet();
            operation.delete();
        }

        @Override
        protected void commitDeletion(IDeleteOperation operation) throws IOException {
            counter.incrementAndGet();
            operation.delete();
        }

        @Override
        protected void commitComplete() {
        }
    };

    File queue = temp.newFolder();
    committer.setQueueDir(queue.getPath());
    // Use a bigger number to make sure the files are not 
    // committed while they are added.
    committer.setQueueSize(1000);

    // Queue 50 files for additions
    for (int i = 0; i < 50; i++) {
        Properties metadata = new Properties();
        committer.add(Integer.toString(i), IOUtils.toInputStream("hello world!"), metadata);
    }
    // Queue 50 files for deletions
    for (int i = 50; i < 100; i++) {
        Properties metadata = new Properties();
        committer.remove(Integer.toString(i), metadata);
    }

    ExecutorService pool = Executors.newFixedThreadPool(10);
    for (int i = 0; i < 10; i++) {
        pool.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    committer.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

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

    // Each file should have been processed exactly once
    assertEquals(100, counter.intValue());

    // All files should have been processed
    Collection<File> files = FileUtils.listFiles(queue, null, true);
    assertTrue(files.isEmpty());
}

From source file:com.netflix.curator.framework.recipes.barriers.TestDistributedBarrier.java

@Test
public void testNoBarrier() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    try {//from w  ww . j  av a  2  s.  c o m
        client.start();

        final DistributedBarrier barrier = new DistributedBarrier(client, "/barrier");
        Assert.assertTrue(barrier.waitOnBarrier(10, TimeUnit.SECONDS));

        // just for grins, test the infinite wait
        ExecutorService service = Executors.newSingleThreadExecutor();
        Future<Object> future = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                barrier.waitOnBarrier();
                return "";
            }
        });
        Assert.assertTrue(future.get(10, TimeUnit.SECONDS) != null);
    } finally {
        client.close();
    }
}