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:de.slackspace.wfail2ban.logfile.impl.ContinuousLogfileReader.java

@Override
protected void doParsing(Filter filter, FilterResultHandler callback) {
    TailerListener listener = new ContinuousTailerListener(filter, callback);
    Tailer tailer = new Tailer(new File(filter.getLogfilePath()), listener);

    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.submit(tailer);
}

From source file:com.twitter.graphjet.bipartite.edgepool.EdgePoolConcurrentTestHelper.java

/**
 * This helper method sets up a concurrent read-write situation with a single writer and multiple
 * readers that access the same underlying edgePool, and tests for correct edge access after
 * every single edge write via latches. This helps test write flushing after every edge insertion.
 *
 * @param edgePool    is the underlying {@link com.twitter.graphjet.bipartite.edgepool.EdgePool}
 * @param edgesToAdd  is a list of edges to add in the graph
 * @return the readers that store the state that they saw so that the state can be tested. There
 *         is a reader for every edge insertion.
 */// w  w w  .  ja  v  a2 s. c om
public static List<EdgePoolReader> runConcurrentReadWriteThreads(EdgePool edgePool,
        List<Pair<Integer, Integer>> edgesToAdd) {
    int numReaders = edgesToAdd.size(); // start reading after first edge is written
    ExecutorService executor = Executors.newFixedThreadPool(numReaders + 1); // single writer

    List<CountDownLatch> readerStartLatches = Lists.newArrayListWithCapacity(numReaders);
    List<CountDownLatch> readerDoneLatches = Lists.newArrayListWithCapacity(numReaders);
    List<EdgePoolReader> readers = Lists.newArrayListWithCapacity(numReaders);

    for (Pair<Integer, Integer> edge : edgesToAdd) {
        CountDownLatch startLatch = new CountDownLatch(1);
        CountDownLatch doneLatch = new CountDownLatch(1);
        // Each time, get edges for the node added in the previous step
        EdgePoolReader edgePoolReader = new EdgePoolReader(edgePool, startLatch, doneLatch, edge.getLeft(), 0);
        readers.add(edgePoolReader);
        executor.submit(edgePoolReader);
        readerStartLatches.add(startLatch);
        readerDoneLatches.add(doneLatch);
    }

    /**
     * The start/done latches achieve the following execution order: writer, then reader 1, then
     * writer, then reader 2, and so on. As a concrete example, suppose we have two readers and a
     * writer, then the start/done latches are used as follows:
     * Initial latches state:
     * s1 = 1, d1 = 1
     * s2 = 1, d2 = 1
     * Execution steps:
     * - writer writes edge 1, sets s1 = 0 and waits on d1
     * - reader 1 reads since s1 == 0 and sets d1 = 0
     * - writer writes edge 2, sets s2 = 0 and waits on d2
     * - reader 2 reads since s2 == 0 and sets d2 = 0
     */
    List<WriterInfo> writerInfo = Lists.newArrayListWithCapacity(edgesToAdd.size());
    for (int i = 0; i < numReaders; i++) {
        // Start writing immediately at first, but then write an edge once the reader finishes reading
        // the previous edge
        CountDownLatch startLatch = (i > 0) ? readerDoneLatches.get(i - 1) : new CountDownLatch(0);
        // Release the next reader
        CountDownLatch doneLatch = readerStartLatches.get(i);
        writerInfo.add(new WriterInfo(edgesToAdd.get(i).getLeft(), edgesToAdd.get(i).getRight(), startLatch,
                doneLatch));
    }

    executor.submit(new EdgePoolWriter(edgePool, writerInfo));

    // Wait for all the processes to finish and then confirm that they did what they worked as
    // expected
    try {
        readerDoneLatches.get(numReaders - 1).await();
    } catch (InterruptedException e) {
        throw new RuntimeException("Execution for last reader was interrupted: ", e);
    }
    return readers;
}

From source file:com.autsia.socialboot.SocialBootApplicationTests.java

@Test
public void performanceTest() throws Exception {
    final IQueue<Object> queue = hazelcastInstance.getQueue(SocialBootApplication.class.getSimpleName());

    ExecutorService threadPool = Executors.newFixedThreadPool(1);
    threadPool.submit((Runnable) () -> {
        while (true) {
            String id = String.valueOf(ThreadLocalRandom.current().nextLong());
            twitterService.consumeTweetFromExternalSystem(id, text);
        }//from w w w . j  av  a2 s .co  m
    });
    while (queue.isEmpty()) {
        Thread.sleep(1000);
    }
    int countBefore = queue.size();
    Thread.sleep(MEASUREMENT_DELAY);
    int countAfter = queue.size();
    LOGGER.info("Tweets processed: {}", countAfter - countBefore);
}

From source file:pzalejko.iot.hardware.home.core.app.Application.java

/**
 * Starts all services.//from   w  w w  .  ja  v a2 s.  c o m
 * <p>
 * NOTE: When this method is done then the application can be closed.
 *
 * @throws ExecutionException if a task cannot be started.
 * @throws InterruptedException if a task has been interrupted.
 */
public void start() throws ExecutionException, InterruptedException {
    LOG.debug(LogMessages.STARTING_APPLICATION);

    taskExecutor.executeRepeatable(temperatureTask, temperatureTask.getReadFrequency());
    taskExecutor.execute(remoteLedControlTask);
    taskExecutor.execute(ledAlertTask);

    final ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(shutDownTask).get();
}

From source file:com.mgmtp.perfload.core.test.comp.ComponentTest.java

@BeforeTest
public void startDaemon() throws IOException {
    log.debug("Starting daemon...");

    ExecutorService executorService = Executors.newFixedThreadPool(2, new DaemonThreadFactory());
    executorService.submit(new DaemonTask(DAEMON_PORT));
}

From source file:com.mobius.software.mqtt.performance.runner.ScenarioRunner.java

public void start() throws InterruptedException {
    List<RequestWorker> workers = new ArrayList<>();
    CountDownLatch latch = new CountDownLatch(requests.size());
    for (ScenarioRequest request : requests)
        workers.add(new RequestWorker(request, latch));

    ExecutorService service = Executors.newFixedThreadPool(workers.size());
    for (RequestWorker worker : workers)
        service.submit(worker);
    latch.await();//from  ww w  .j a v  a2 s.co  m

    service.shutdownNow();
}

From source file:apiserver.services.pdf.service.ExtractPdfFormFieldsCFService.java

public Object execute(Message<?> message) throws ColdFusionException {
    ExtractPdfFormResult props = (ExtractPdfFormResult) message.getPayload();

    try {//  ww  w.j av a 2s.  c om
        long startTime = System.nanoTime();
        Grid grid = verifyGridConnection();

        // Get grid-enabled executor service for nodes where attribute 'worker' is defined.
        ExecutorService exec = getColdFusionExecutor();

        Future<MapResult> future = exec.submit(new ExtractFormFieldsCallable(props.getFile().getFileBytes()));

        MapResult _result = future.get(defaultTimeout, TimeUnit.SECONDS);
        props.setResult(_result.getData());

        long endTime = System.nanoTime();
        log.debug("execution times: CF=" + _result.getStats().getExecutionTime() + "ms -- total="
                + (endTime - startTime) + "ms");

        return props;
    } catch (Exception ge) {
        throw new RuntimeException(ge);
    }
}

From source file:apiserver.services.pdf.service.GetPdfInfoCFService.java

public Object execute(Message<?> message) throws ColdFusionException {
    PdfGetInfoResult props = (PdfGetInfoResult) message.getPayload();

    try {//  w  w w .java  2s.  co  m
        long startTime = System.nanoTime();
        Grid grid = verifyGridConnection();

        // Get grid-enabled executor service for nodes where attribute 'worker' is defined.
        ExecutorService exec = getColdFusionExecutor();

        Future<MapResult> future = exec
                .submit(new GetInfoCallable(props.getFile().getFileBytes(), props.getOptions()));

        MapResult _result = future.get(defaultTimeout, TimeUnit.SECONDS);
        props.setResult(_result.getData());

        long endTime = System.nanoTime();
        log.debug("execution times: CF=" + _result.getStats().getExecutionTime() + "ms -- total="
                + (endTime - startTime) + "ms");

        return props;
    } catch (Exception ge) {
        throw new RuntimeException(ge);
    }
}

From source file:apiserver.services.pdf.service.SetPdfInfoCFService.java

public Object execute(Message<?> message) throws ColdFusionException {
    PdfSetInfoResult props = (PdfSetInfoResult) message.getPayload();

    try {/*from  ww w . j  a v  a2s  .c  o  m*/
        long startTime = System.nanoTime();
        Grid grid = verifyGridConnection();

        // Get grid-enabled executor service for nodes where attribute 'worker' is defined.
        ExecutorService exec = getColdFusionExecutor();

        Future<MapResult> future = exec
                .submit(new SetInfoCallable(props.getFile().getFileBytes(), props.getOptions()));

        MapResult _result = future.get(defaultTimeout, TimeUnit.SECONDS);
        props.setResult(_result.getData());

        long endTime = System.nanoTime();
        log.debug("execution times: CF=" + _result.getStats().getExecutionTime() + "ms -- total="
                + (endTime - startTime) + "ms");

        return props;
    } catch (Exception ge) {
        throw new RuntimeException(ge);
    }
}

From source file:br.com.uol.runas.service.JUnitService.java

public JUnitServiceResponse runTests(String path, final String[] suites) throws Exception {
    try (final JarClassLoader classLoader = new JarClassLoader(path, classLoaderGC)) {
        final ThreadFactory threadFactory = new ThreadFactoryImpl(classLoader);

        final ExecutorService service = Executors.newSingleThreadExecutor(threadFactory);

        try {/* w w w.j a va2  s  . c om*/
            return service.submit(new JUnitTask(suites)).get();
        } finally {
            service.shutdownNow();
        }
    }
}