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.vmware.bdd.utils.CommonUtil.java

/**
*
* @param host/*  ww  w . ja  v a 2  s. co m*/
* @param port
* @param waitTime
*/
public static boolean checkServerConnection(final String host, final int port, int waitTime) {
    boolean connectResult = false;

    // validate the server is reachable
    ExecutorService exec = Executors.newFixedThreadPool(1);
    try {
        // if the target ip does not exist or the host is shutdown, it will take about 2 minutes
        // for the socket connection to time out.
        // here we fork a child thread to do the actual connecting action, if it does not succeed
        // within given waitTime, we will consider it to be failure.
        Future<Boolean> futureResult = exec.submit(new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                try {
                    new Socket(host, port);
                    return true;
                } catch (Exception e) {
                }
                return false;
            }
        });

        // wait for the thread to finish within given waitTime
        Boolean result = (Boolean) waitForThreadResult(futureResult, waitTime);

        // result==null means the time out occurs
        if (null != result) {
            connectResult = result;
        }
    } catch (Exception e) {
        logger.error("Unexpected error occurred with threading.");
    } finally {
        if (null != exec) {
            exec.shutdown();
        }
    }

    return connectResult;
}

From source file:gobblin.configuration.StateTest.java

/**
 * This test checks that state object is thread safe. We run 2 threads, one of them continuously adds and removes key/values
 * to the state and other thread calls getProperties.
 *///from   w w w . j a v  a  2s  .  co m
@Test
public void testGetPropertiesThreadSafety() {
    try {
        final State state = new State();
        for (int i = 0; i < 1000; i++) {
            state.setProp(Integer.toString(i), Integer.toString(i));
        }
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; j < 1000; j++) {
                    for (int i = 0; i < 1000; i++) {
                        try {
                            state.removeProp(Integer.toString(i));
                            state.setProp(Integer.toString(i), Integer.toString(i));
                        } catch (Throwable t) {
                            exceptions.add(t);
                        }
                    }
                }
            }
        });

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    try {
                        state.getProperties().get(Integer.toString(i));
                    } catch (Throwable t) {
                        exceptions.add(t);
                    }
                }
            }
        });

        executorService.shutdown();
        if (!executorService.awaitTermination(100, TimeUnit.SECONDS)) {
            throw new RuntimeException("Executor service still running");
        }
    } catch (Throwable t) {
        Assert.fail("Concurrency test failed", t);
    }

    if (!this.exceptions.isEmpty()) {
        Assert.fail("Concurrency test failed with first exception: "
                + ExceptionUtils.getFullStackTrace(this.exceptions.poll()));
    }
}

From source file:com.newlandframework.avatarmq.core.SendMessageCache.java

public void parallelDispatch(LinkedList<MessageDispatchTask> list) {
    List<Callable<Void>> tasks = new ArrayList<Callable<Void>>();
    int startPosition = 0;
    Pair<Integer, Integer> pair = calculateBlocks(list.size(), list.size());
    int numberOfThreads = pair.getRight();
    int blocks = pair.getLeft();

    for (int i = 0; i < numberOfThreads; i++) {
        MessageDispatchTask[] task = new MessageDispatchTask[blocks];
        phaser.register();/*from   w w w  . ja  v a 2  s. co  m*/
        System.arraycopy(list.toArray(), startPosition, task, 0, blocks);
        tasks.add(new SendMessageTask(phaser, task));
        startPosition += blocks;
    }

    ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
    for (Callable<Void> element : tasks) {
        executor.submit(element);
    }
}

From source file:io.cloudslang.content.utilities.util.ProcessExecutor.java

public ProcessResponseEntity execute(String commandLine, int timeout)
        throws IOException, ExecutionException, InterruptedException, TimeoutException {
    Process process = new ProcessBuilder().command(processCommand(commandLine)).start();

    ProcessStreamConsumer processStreamConsumer = new ProcessStreamConsumer(process);
    ExecutorService executor = Executors.newFixedThreadPool(1);
    Future<ProcessResponseEntity> futureResult = executor.submit(processStreamConsumer);

    try {//from   w ww . ja v  a2 s  .c om
        return futureResult.get(timeout, MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        stopProcess(process, futureResult);
        throw e;
    } finally {
        executor.shutdownNow();
    }
}

From source file:infrascructure.data.readers.AdvancedResourcesRepository.java

@Override
public void readAll() throws IOException {
    int threads = config.getPropertyInt(Config.CRAWL_THREADS, 1);
    int i = rawdocs.size();
    index = new AtomicInteger(i);

    ExecutorService pool = Executors.newCachedThreadPool();
    for (int t = 0; t < threads; t++) {
        pool.submit(this);
    }/*from   w w  w . jav  a  2s.  c  o m*/
}

From source file:de.huberlin.wbi.hiway.am.cuneiform.CuneiformApplicationMaster.java

public CuneiformApplicationMaster() {
    super();//from   ww  w .j a va2 s  . co  m
    ExecutorService executor = Executors.newCachedThreadPool();

    creActor = new HiWayCreActor(this);
    executor.submit(creActor);

    ticketSrc = new TicketSrcActor(creActor);
    executor.submit(ticketSrc);
    executor.shutdown();
}

From source file:biz.fstechnology.micro.common.jms.JmsServiceConnection.java

/**
 * @see biz.fstechnology.micro.common.DefaultServiceConnection#callAsync(biz.fstechnology.micro.common.Request,
 * java.util.function.Consumer)//w  w w.j  a va2s . c o  m
 */
@Override
public <T, U> void callAsync(Request<T> request, Consumer<Result<U>> callback) {
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Result<U>> rawResponse = executor.submit(() -> call(request));
    executor.submit(() -> {
        try {
            callback.accept(rawResponse.get());
        } catch (Exception e) {
            e.printStackTrace();
            Result<U> result = new Result<>(e);
            callback.accept(result);
        }
    });
    executor.shutdown();
}

From source file:org.ops4j.orient.spring.tx.blueprints.OrientGraphTransactionTest.java

@Test
public void commitMultiThreaded() throws InterruptedException {

    ExecutorService executorService = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 5; i++) {
        executorService.submit(new CommitTask());
    }/*  w w w.  j a v a  2s.c o m*/
    executorService.shutdown();
    executorService.awaitTermination(1000, TimeUnit.SECONDS);
}

From source file:org.ops4j.orient.spring.tx.document.DocumentDatabaseTransactionTest.java

@Test
public void commitMultiThreaded() throws InterruptedException {

    ExecutorService executorService = Executors.newFixedThreadPool(5);
    for (int i = 0; i < 5; i++) {
        executorService.submit(new CommitTask());
    }/*from  w  w  w .j  a va2 s .c  o  m*/
    executorService.shutdown();
    executorService.awaitTermination(1000, TimeUnit.SECONDS);

}

From source file:com.topekalabs.synchronization.LockTest.java

@Test
public void testLockAndUnlock() {
    final long timeout = 500;

    ExecutorService es = Executors.newSingleThreadExecutor();
    Future<Integer> future = es.submit(new Callable<Integer>() {
        @Override//from   w w w  .  j a v a  2 s . c o m
        public Integer call() throws Exception {
            Lock lock = lockClass.newInstance();
            lock.lock();
            lock.unlock();
            return 1;
        }
    });

    try {
        future.get(timeout, TimeUnit.MILLISECONDS);
    } catch (InterruptedException | ExecutionException | TimeoutException ex) {
        ErrorThrower.kill(ex);
    }

    es.shutdown();
}