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:net.openhft.chronicle.logger.slf4j.Slf4jIndexedChronicleBinaryLoggerPerfTest.java

@Test
public void testMultiThreadLogging() throws IOException, InterruptedException {
    warmup(LoggerFactory.getLogger("perf-binary-indexed-chronicle"));

    final int RUNS = 1000000;
    final int THREADS = 10;

    for (int size : new int[] { 64, 128, 256 }) {
        final long start = System.nanoTime();

        ExecutorService es = Executors.newFixedThreadPool(THREADS);
        for (int t = 0; t < THREADS; t++) {
            es.submit(new RunnableLogger(RUNS, size, "perf-binary-indexed-chronicle"));
        }/*from w  w  w .  ja  v  a 2s  . co m*/

        es.shutdown();
        es.awaitTermination(30, TimeUnit.SECONDS);

        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));
    }

    ChronicleTools.deleteOnExit(basePath("perf-binary-indexed-chronicle"));
}

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 {/*  w w  w. ja  v a2s  . c o  m*/
        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.barchart.udt.TestSocketFile.java

/**
 * verify basic file send/receive/*from  ww  w .  j a  v  a2 s.c o  m*/
 */
@Test(timeout = 10 * 1000)
public void fileTransfer() throws Exception {

    final InetSocketAddress addr1 = localSocketAddress();
    final InetSocketAddress addr2 = localSocketAddress();

    final SocketUDT peer1 = new SocketUDT(TypeUDT.STREAM);
    final SocketUDT peer2 = new SocketUDT(TypeUDT.STREAM);

    peer1.setBlocking(false);
    peer2.setBlocking(false);

    peer1.setRendezvous(true);
    peer2.setRendezvous(true);

    peer1.bind(addr1);
    peer2.bind(addr2);

    socketAwait(peer1, StatusUDT.OPENED);
    socketAwait(peer2, StatusUDT.OPENED);

    peer1.connect(addr2);
    peer2.connect(addr1);

    socketAwait(peer1, StatusUDT.CONNECTED);
    socketAwait(peer2, StatusUDT.CONNECTED);

    log.info("state 0 - connected");
    log.info("peer1 : {}", peer1);
    log.info("peer2 : {}", peer2);

    final int size = 64 * 1024;

    final Random random = new Random(0);
    final byte[] array1 = new byte[size];
    final byte[] array2 = new byte[size];
    random.nextBytes(array1);
    random.nextBytes(array2);

    final File folder = new File("./target/file");
    folder.mkdirs();

    final File source = File.createTempFile("source", "data", folder);
    final File target = File.createTempFile("target", "data", folder);

    FileUtils.writeByteArrayToFile(source, array1);
    FileUtils.writeByteArrayToFile(target, array2);

    assertEquals(size, source.length());
    assertEquals(size, target.length());

    assertFalse("files are different", FileUtils.contentEquals(source, target));

    // sender
    final Runnable task1 = new Runnable() {
        @Override
        public void run() {
            try {
                log.info("init send");
                final long length = peer1.sendFile(source, 0, size);
                assertEquals(length, size);
            } catch (final Exception e) {
                log.error("", e);
            }
        }
    };

    // receiver
    final Runnable task2 = new Runnable() {
        @Override
        public void run() {
            try {
                log.info("init recv");
                final long length = peer2.receiveFile(target, 0, size);
                assertEquals(length, size);
            } catch (final Exception e) {
                log.error("", e);
            }
        }
    };

    final ExecutorService executor = Executors.newFixedThreadPool(2);

    executor.submit(task1);
    executor.submit(task2);

    Thread.sleep(5 * 1000);

    executor.shutdownNow();

    assertTrue("files are the same", FileUtils.contentEquals(source, target));

    peer1.close();
    peer2.close();

}

From source file:com.asakusafw.runtime.directio.hadoop.HadoopDataSourceUtil.java

private static void parallel(ExecutorService executor, Collection<? extends Callable<?>> tasks)
        throws IOException, InterruptedException {
    List<Future<?>> futures = tasks.stream().map(task -> executor.submit(task)).collect(Collectors.toList());
    for (Future<?> future : futures) {
        try {/*from   w  ww.  j ava 2  s  .c om*/
            future.get();
        } catch (CancellationException | InterruptedException e) {
            cancel(futures);
            throw e;
        } catch (ExecutionException e) {
            cancel(futures);
            try {
                throw e.getCause();
            } catch (Error | RuntimeException | IOException | InterruptedException cause) {
                throw cause;
            } catch (Throwable cause) {
                throw new IOException(cause);
            }
        }
    }
}

From source file:se.omegapoint.facepalm.infrastructure.FilePolicyRepository.java

@Override
public Optional<Policy> retrievePolicyWith(final String filename) {
    notBlank(filename);/*www . ja va2s.  co  m*/

    final ExecutorService executorService = Executors.newSingleThreadExecutor();
    final Command command = commandBasedOnOperatingSystem(filename);
    final Future<String> future = executorService.submit(command);

    try {
        eventService.publish(new GenericEvent(format("About to execute command[%s]", command.command)));
        return Optional.of(new Policy(future.get(TIMEOUT, TimeUnit.SECONDS)));
    } catch (Exception e) {
        return Optional.empty();
    }
}

From source file:com.wenyu.clustertools.SetStreamThroughput.java

@Override
public void execute() {
    ExecutorService executor = Executors.newFixedThreadPool(parallel);

    Map<Node, Future<String>> futures = new HashMap<>();
    for (ClusterToolCmd.Node node : nodes) {
        futures.put(node, executor.submit(new Executor(node)));
    }/*from ww  w.j  a  va2s  .c om*/

    for (Map.Entry<ClusterToolCmd.Node, Future<String>> future : futures.entrySet()) {
        try {
            String result = future.getValue().get(Constants.MAX_PARALLEL_WAIT_IN_SEC, TimeUnit.SECONDS);
            System.out.println(result);
        } catch (Exception ex) {
            System.out
                    .println(String.format("%s failed with error: %s", future.getKey().server, ex.toString()));
            ex.printStackTrace();
        }
    }
}

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

@Test
public void testServerCrash() throws Exception {
    final int TIMEOUT = 1000;

    final CuratorFramework client = CuratorFrameworkFactory.builder().connectString(server.getConnectString())
            .connectionTimeoutMs(TIMEOUT).retryPolicy(new RetryOneTime(1)).build();
    try {//from w  w w .  j  av a  2 s  .co  m
        client.start();

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

        final ExecutorService service = Executors.newSingleThreadExecutor();
        Future<Object> future = service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Thread.sleep(TIMEOUT / 2);
                server.stop();
                return null;
            }
        });

        barrier.waitOnBarrier(TIMEOUT * 2, TimeUnit.SECONDS);
        future.get();
        Assert.fail();
    } catch (KeeperException.ConnectionLossException expected) {
        // expected
    } finally {
        client.close();
    }
}

From source file:net.openhft.chronicle.logger.slf4j.Slf4jIndexedChronicleLoggerPerfTest.java

@Test
public void testMultiThreadLogging() throws IOException, InterruptedException {
    warmup(LoggerFactory.getLogger("perf-binary-indexed-chronicle"));

    final int RUNS = 1000000;
    final int THREADS = 10;

    for (int size : new int[] { 64, 128, 256 }) {
        {//  w ww . j av a  2 s  . 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, "perf-binary-indexed-chronicle"));
            }

            es.shutdown();
            es.awaitTermination(5, TimeUnit.SECONDS);

            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));
        }
    }

    ChronicleTools.deleteOnExit(basePath("perf-binary-indexed-chronicle"));
}

From source file:net.openhft.chronicle.logger.slf4j.Slf4jVanillaChronicleBinaryLoggerPerfTest.java

@Test
public void testMultiThreadLogging() throws IOException, InterruptedException {
    warmup(LoggerFactory.getLogger("perf-binary-vanilla-chronicle"));

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

    for (int size : new int[] { 64, 128, 256 }) {
        {/*from   www .  j a v  a 2s .c  o  m*/
            final long start = System.nanoTime();

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

            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));
        }
    }

    ChronicleTools.deleteOnExit(basePath("perf-binary-vanilla-chronicle"));
}

From source file:net.openhft.chronicle.logger.slf4j.Slf4jVanillaChronicleLoggerPerfTest.java

@Test
public void testMultiThreadLogging() throws IOException, InterruptedException {
    warmup(LoggerFactory.getLogger("perf-vanilla-chronicle"));

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

    for (int size : new int[] { 64, 128, 256 }) {
        {//from  w  ww  .j  a v a2  s.  c  o m
            final long start = System.nanoTime();

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

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

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

            System.out.printf(
                    "Plain.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));
        }
    }

    ChronicleTools.deleteOnExit(basePath("perf-vanilla-chronicle"));
}