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.palantir.paxos.PaxosConsensusFastTest.java

@Test
public void loseQuorumDiffToken() throws InterruptedException {
    for (int i = QUORUM_SIZE; i < NUM_POTENTIAL_LEADERS; i++) {
        state.goDown(i);//from w  ww  . j  a v a 2  s  .  c o m
    }
    LeadershipToken t = state.gainLeadership(0);
    state.goDown(QUORUM_SIZE - 1);
    ExecutorService exec = PTExecutors.newSingleThreadExecutor();
    Future<Void> f = exec.submit(new Callable<Void>() {
        @Override
        public Void call() {
            int i = QUORUM_SIZE - 1;
            while (!Thread.currentThread().isInterrupted()) {
                int next = i + 1;
                if (next == NUM_POTENTIAL_LEADERS) {
                    next = QUORUM_SIZE - 1;
                }
                state.goDown(next);
                state.comeUp(i);
                i = next;
            }
            return null;
        }
    });
    // Don't check leadership immediately after gaining it, since quorum might get lost.
    LeadershipToken token2 = state.gainLeadershipWithoutCheckingAfter(0);
    assertTrue("leader can confirm leadership with quorum", t.sameAs(token2));
    f.cancel(true);
    exec.shutdown();
    exec.awaitTermination(10, TimeUnit.SECONDS);
    for (int i = 0; i < NUM_POTENTIAL_LEADERS; i++) {
        state.comeUp(i);
    }
}

From source file:com.xeiam.xchange.examples.mtgox.v2.service.trade.streaming.MtGoxWebSocketTradeDemo.java

public void start() throws ExecutionException, InterruptedException {

    // Use the default MtGox settings
    Exchange mtGoxExchange = MtGoxV2ExamplesUtils.createExchange();

    ExchangeStreamingConfiguration exchangeStreamingConfiguration = new MtGoxStreamingConfiguration(10, 10000,
            60000, false, null);//from  ww w.  j a  v a 2s .  c  o m

    // Interested in the public streaming market data feed (no authentication)
    StreamingExchangeService streamingExchangeService = mtGoxExchange
            .getStreamingExchangeService(exchangeStreamingConfiguration);

    // Open the connections to the exchange
    streamingExchangeService.connect();

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future<?> mtGoxMarketDataFuture = executorService
            .submit(new TradeDataRunnable(streamingExchangeService, mtGoxExchange));

    // the thread waits here until the Runnable is done.
    mtGoxMarketDataFuture.get();

    executorService.shutdown();

    // Disconnect and exit
    System.out.println(Thread.currentThread().getName() + ": Disconnecting...");
    streamingExchangeService.disconnect();
}

From source file:com.espertech.esper.multithread.TestMTStmtNamedWindowSubqueryLookup.java

private void trySend(int numThreads, int numEventsPerThread) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    config.getEngineDefaults().getEventMeta()
            .setDefaultEventRepresentation(Configuration.EventRepresentation.MAP); // use Map-type events for testing
    config.addEventType("SupportBean", SupportBean.class);
    engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();/* w w  w .  jav a  2  s  . c om*/

    // setup statements
    engine.getEPAdministrator().createEPL("create schema MyUpdateEvent as (key string, intupd int)");
    engine.getEPAdministrator().createEPL("create schema MySchema as (theString string, intval int)");
    EPStatement namedWindow = engine.getEPAdministrator()
            .createEPL("create window MyWindow.win:keepall() as MySchema");
    engine.getEPAdministrator()
            .createEPL("on MyUpdateEvent mue merge MyWindow mw " + "where mw.theString = mue.key "
                    + "when not matched then insert select key as theString, intupd as intval "
                    + "when matched then delete");
    EPStatement targetStatement = engine.getEPAdministrator().createEPL(
            "select (select intval from MyWindow mw where mw.theString = sb.theString) as val from SupportBean sb");

    // execute
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future<Boolean> future[] = new Future[numThreads];
    for (int i = 0; i < numThreads; i++) {
        future[i] = threadPool.submit(
                new StmtNamedWindowSubqueryLookupCallable(i, engine, numEventsPerThread, targetStatement));
    }

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

    // total up result
    for (int i = 0; i < numThreads; i++) {
        Boolean result = future[i].get();
        assertTrue(result);
    }

    EventBean[] events = EPAssertionUtil.iteratorToArray(namedWindow.iterator());
    assertEquals(0, events.length);
}

From source file:com.developmentsprint.spring.breaker.hystrix.HystrixAnnotationDrivenConcreteClassTest.java

@Test
public void testMaxConcurrency() throws Exception {
    ExecutorService executor = Executors.newFixedThreadPool(20);
    List<Future<String>> futures = new ArrayList<Future<String>>();
    for (int i = 0; i < 20; i++) {
        futures.add(executor.submit(new Callable<String>() {
            @Override//from   ww  w .j  a  v  a2 s.  co  m
            public String call() throws Exception {
                return methods.getText();
            }
        }));
    }

    Thread.sleep(500L);

    int successes = 0;
    int rejections = 0;
    for (Future<String> future : futures) {
        try {
            future.get();
            successes++;
        } catch (Exception e) {
            rejections++;
        }
    }

    assertThat(successes).isEqualTo(10);
    assertThat(rejections).isEqualTo(10);
}

From source file:ch.epfl.eagle.daemon.nodemonitor.TaskLauncherService.java

public void initialize(Configuration conf, TaskScheduler scheduler, int nodeMonitorPort) {
    numThreads = scheduler.getMaxActiveTasks();
    if (numThreads <= 0) {
        // If the scheduler does not enforce a maximum number of tasks, just use a number of
        // threads equal to the number of cores.
        numThreads = Resources.getSystemCPUCount(conf);
    }// ww w  .j  a va  2 s.c  o m
    this.scheduler = scheduler;
    nodeMonitorInternalAddress = new THostPort(Network.getIPAddress(conf), nodeMonitorPort);
    ExecutorService service = Executors.newFixedThreadPool(numThreads);
    for (int i = 0; i < numThreads; i++) {
        service.submit(new TaskLaunchRunnable());
    }
}

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

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

    Map<ClusterToolCmd.Node, Future<String>> futures = new HashMap<>();
    for (ClusterToolCmd.Node node : nodes) {
        futures.put(node, executor.submit(new Executor(node)));
    }//  w w  w  .j  a v a2s .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.espertech.esper.multithread.TestMTDeterminismListener.java

private void trySend(int numThreads, int numEvents, boolean isPreserveOrder,
        ConfigurationEngineDefaults.Threading.Locking locking) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    config.getEngineDefaults().getThreading().setListenerDispatchPreserveOrder(isPreserveOrder);
    config.getEngineDefaults().getThreading().setListenerDispatchLocking(locking);

    engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();/*  w w  w.ja va2 s .  c o  m*/

    // setup statements
    EPStatement stmtInsert = engine.getEPAdministrator()
            .createEPL("select count(*) as cnt from " + SupportBean.class.getName());
    SupportMTUpdateListener listener = new SupportMTUpdateListener();
    stmtInsert.addListener(listener);

    // execute
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future future[] = new Future[numThreads];
    for (int i = 0; i < numThreads; i++) {
        future[i] = threadPool.submit(new SendEventCallable(i, engine, new GeneratorIterator(numEvents)));
    }

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

    for (int i = 0; i < numThreads; i++) {
        assertTrue((Boolean) future[i].get());
    }

    EventBean events[] = listener.getNewDataListFlattened();
    long[] result = new long[events.length];
    for (int i = 0; i < events.length; i++) {
        result[i] = (Long) events[i].get("cnt");
    }
    //log.info(".trySend result=" + Arrays.toString(result));

    // assert result
    assertEquals(numEvents * numThreads, events.length);
    for (int i = 0; i < numEvents * numThreads; i++) {
        assertEquals(result[i], (long) i + 1);
    }
}

From source file:Main.java

public void processUsers(int numOfWorkerThreads) {
    ExecutorService threadPool = Executors.newFixedThreadPool(numOfWorkerThreads);
    int chunk = itemsToBeProcessed.length / numOfWorkerThreads;
    int start = 0;
    List<Future> tasks = new ArrayList<Future>();
    for (int i = 0; i < numOfWorkerThreads; i++) {
        tasks.add(threadPool.submit(new WorkerThread(start, start + chunk)));
        start = start + chunk;//from   w  ww  .  j a  va 2  s.c  o m
    }
    // join all worker threads to main thread
    for (Future f : tasks) {
        try {
            f.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    threadPool.shutdown();
    while (!threadPool.isTerminated()) {
    }
}

From source file:com.espertech.esper.multithread.TestMTStmtNamedWindowMerge.java

private void trySend(int numThreads, int numEventsPerThread) throws Exception {
    Configuration config = SupportConfigFactory.getConfiguration();
    config.addEventType("SupportBean", SupportBean.class);
    engine = EPServiceProviderManager.getDefaultProvider(config);
    engine.initialize();//  w  w w .  j  a  v  a2  s . com

    // setup statements
    engine.getEPAdministrator().createEPL("create window MyWindow.win:keepall() as select * from SupportBean");
    engine.getEPAdministrator()
            .createEPL("on SupportBean sb " + "merge MyWindow nw where nw.theString = sb.theString "
                    + " when not matched then insert select * "
                    + " when matched then update set intPrimitive = nw.intPrimitive + 1");

    // execute
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future<Boolean> future[] = new Future[numThreads];
    for (int i = 0; i < numThreads; i++) {
        future[i] = threadPool.submit(new StmtNamedWindowMergeCallable(engine, numEventsPerThread));
    }

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

    // total up result
    for (int i = 0; i < numThreads; i++) {
        Boolean result = future[i].get();
        assertTrue(result);
    }

    // compare
    EventBean[] rows = engine.getEPRuntime().executeQuery("select * from MyWindow").getArray();
    assertEquals(numEventsPerThread, rows.length);
    for (EventBean row : rows) {
        assertEquals(numThreads - 1, row.get("intPrimitive"));
    }
    //long deltaTime = endTime - startTime;
    //System.out.println("Totals updated: " + totalUpdates + "  Delta cumu: " + deltaCumulative + "  Delta pooled: " + deltaTime);
}

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

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

    Map<ClusterToolCmd.Node, Future<Void>> futures = new HashMap<>();
    for (ClusterToolCmd.Node node : nodes) {
        futures.put(node, executor.submit(new Executor(node)));
    }/*from   www .j  a  va2 s  .  co m*/

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