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:hivemall.mix.server.MixServerTest.java

@Test
public void testSimpleScenario() throws InterruptedException {
    int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
            new String[] { "-port", Integer.toString(port), "-sync_threshold", "3" }, MixServer.getOptions());
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);

    waitForState(server, ServerState.RUNNING);

    PredictionModel model = new DenseModel(16777216, false);
    model.configureClock();/* ww w  .  ja v a 2 s.  com*/
    MixClient client = null;
    try {
        client = new MixClient(MixEventName.average, "testSimpleScenario", "localhost:" + port, false, 2,
                model);
        model.configureMix(client, false);

        final Random rand = new Random(43);
        for (int i = 0; i < 100000; i++) {
            Integer feature = Integer.valueOf(rand.nextInt(100));
            float weight = (float) rand.nextGaussian();
            model.set(feature, new WeightValue(weight));
        }

        Thread.sleep(5000L);

        long numMixed = model.getNumMixed();
        Assert.assertEquals("number of mix events: " + numMixed, numMixed, 0L);

        serverExec.shutdown();
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:hivemall.mix.server.MixServerTest.java

@Test
public void testSSL() throws InterruptedException {
    int port = NetUtils.getAvailablePort();
    CommandLine cl = CommandLineUtils.parseOptions(
            new String[] { "-port", Integer.toString(port), "-sync_threshold", "3", "-ssl" },
            MixServer.getOptions());//  w w w. ja va  2  s .co  m
    MixServer server = new MixServer(cl);
    ExecutorService serverExec = Executors.newSingleThreadExecutor();
    serverExec.submit(server);

    waitForState(server, ServerState.RUNNING);

    PredictionModel model = new DenseModel(16777216, false);
    model.configureClock();
    MixClient client = null;
    try {
        client = new MixClient(MixEventName.average, "testSSL", "localhost:" + port, true, 2, model);
        model.configureMix(client, false);

        final Random rand = new Random(43);
        for (int i = 0; i < 100000; i++) {
            Integer feature = Integer.valueOf(rand.nextInt(100));
            float weight = (float) rand.nextGaussian();
            model.set(feature, new WeightValue(weight));
        }

        Thread.sleep(5000L);

        long numMixed = model.getNumMixed();
        Assert.assertEquals("number of mix events: " + numMixed, numMixed, 0L);

        serverExec.shutdown();
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.blacklocus.jres.request.index.JresUpdateDocumentScriptTest.java

@Test(expected = ExecutionException.class)
public void testRetryOnConflictExpectError() throws InterruptedException, ExecutionException {
    final String index = "JresUpdateDocumentScriptTest.testRetryOnConflictExpectError".toLowerCase();
    final String type = "test";
    final String id = "warzone";

    final AtomicReference<String> error = new AtomicReference<String>();
    final int numThreads = 16, numIterations = 100;

    ExecutorService x = Executors.newFixedThreadPool(numThreads);
    List<Future<?>> futures = new ArrayList<Future<?>>(numThreads);
    for (int i = 0; i < numThreads; i++) {
        futures.add(x.submit(new Callable<Void>() {
            @Override//from ww  w .j a v a 2 s  .c o  m
            public Void call() throws Exception {
                for (int j = 0; j < numIterations; j++) {
                    jres.quest(new JresUpdateDocumentScript(index, type, id, "ctx._source.value += 1", null,
                            ImmutableMap.of("value", 0), null));
                }
                return null;
            }
        }));
    }
    x.shutdown();
    x.awaitTermination(1, TimeUnit.MINUTES);

    for (Future<?> future : futures) {
        // expecting a conflict exception from ElasticSearch
        future.get();
    }
}

From source file:uk.ac.gda.epics.client.pixium.views.PixiumViewController.java

/**
 *///from www  .  j a va 2s  .  com
public Future<Boolean> updateAllFields() {
    ExecutorService executorService = Executors.newFixedThreadPool(3);
    return executorService.submit(updateFields);
}

From source file:com.espertech.esper.multithread.TestMTStmtNamedWindowUpdate.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  a 2  s  .  com*/

    // setup statements
    engine.getEPAdministrator().createEPL(
            "create window MyWindow.std:unique(theString, intPrimitive) as select * from SupportBean");
    engine.getEPAdministrator()
            .createEPL("insert into MyWindow select * from SupportBean(boolPrimitive = true)");
    engine.getEPAdministrator().createEPL("on SupportBean(boolPrimitive = false) sb "
            + "update MyWindow win set intBoxed = win.intBoxed + 1, doublePrimitive = win.doublePrimitive + sb.doublePrimitive"
            + " where sb.theString = win.theString and sb.intPrimitive = win.intPrimitive");

    // send primer events, initialize totals
    Map<MultiKeyUntyped, UpdateTotals> totals = new HashMap<MultiKeyUntyped, UpdateTotals>();
    for (int i = 0; i < NUM_STRINGS; i++) {
        for (int j = 0; j < NUM_INTS; j++) {
            SupportBean primer = new SupportBean(Integer.toString(i), j);
            primer.setBoolPrimitive(true);
            primer.setIntBoxed(0);
            primer.setDoublePrimitive(0);

            engine.getEPRuntime().sendEvent(primer);
            MultiKeyUntyped key = new MultiKeyUntyped(primer.getTheString(), primer.getIntPrimitive());
            totals.put(key, new UpdateTotals(0, 0));
        }
    }

    // execute
    long startTime = System.currentTimeMillis();
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    Future<StmtNamedWindowUpdateCallable.UpdateResult> future[] = new Future[numThreads];
    for (int i = 0; i < numThreads; i++) {
        future[i] = threadPool
                .submit(new StmtNamedWindowUpdateCallable("Thread" + i, engine, numEventsPerThread));
    }

    threadPool.shutdown();
    threadPool.awaitTermination(10, TimeUnit.SECONDS);
    long endTime = System.currentTimeMillis();

    // total up result
    long deltaCumulative = 0;
    for (int i = 0; i < numThreads; i++) {
        StmtNamedWindowUpdateCallable.UpdateResult result = future[i].get();
        deltaCumulative += result.getDelta();
        for (StmtNamedWindowUpdateCallable.UpdateItem item : result.getUpdates()) {
            MultiKeyUntyped key = new MultiKeyUntyped(item.getTheString(), item.getIntval());
            UpdateTotals total = totals.get(key);
            if (total == null) {
                throw new RuntimeException("Totals not found for key " + key);
            }
            total.setNum(total.getNum() + 1);
            total.setSum(total.getSum() + item.getDoublePrimitive());
        }
    }

    // compare
    EventBean[] rows = engine.getEPRuntime().executeQuery("select * from MyWindow").getArray();
    assertEquals(rows.length, totals.size());
    long totalUpdates = 0;
    for (EventBean row : rows) {
        UpdateTotals total = totals.get(new MultiKeyUntyped(row.get("theString"), row.get("intPrimitive")));
        assertEquals(total.getNum(), row.get("intBoxed"));
        assertEquals(total.getSum(), row.get("doublePrimitive"));
        totalUpdates += total.getNum();
    }

    assertEquals(totalUpdates, numThreads * numEventsPerThread);
    //long deltaTime = endTime - startTime;
    //System.out.println("Totals updated: " + totalUpdates + "  Delta cumu: " + deltaCumulative + "  Delta pooled: " + deltaTime);
}

From source file:com.alibaba.otter.shared.arbitrate.zookeeper.DistributedReentrantLockTest.java

@Test
protected void test_lock() {
    ExecutorService exeucotr = Executors.newCachedThreadPool();
    final int count = 50;
    final CountDownLatch latch = new CountDownLatch(count);

    final DistributedReentrantLock lock = new DistributedReentrantLock(dir);
    for (int i = 0; i < count; i++) {
        exeucotr.submit(new Runnable() {

            public void run() {
                try {
                    Thread.sleep(1000);
                    lock.lock();/* www.  ja va2 s . c o  m*/
                    Thread.sleep(100 + RandomUtils.nextInt(100));

                    System.out.println("id: " + lock.getId() + " is leader: " + lock.isOwner());
                } catch (InterruptedException e) {
                    want.fail();
                } catch (KeeperException e) {
                    want.fail();
                } finally {
                    latch.countDown();
                    try {
                        lock.unlock();
                    } catch (KeeperException e) {
                        want.fail();
                    }
                }

            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        want.fail();
    }

    exeucotr.shutdown();
}

From source file:com.alibaba.otter.shared.arbitrate.zookeeper.DistributedReentrantLockTest.java

@Test
protected void test_try_lock() {
    ExecutorService exeucotr = Executors.newCachedThreadPool();
    final int count = 50;
    final CountDownLatch latch = new CountDownLatch(count);

    final DistributedReentrantLock lock = new DistributedReentrantLock(dir);
    for (int i = 0; i < count; i++) {
        exeucotr.submit(new Runnable() {

            public void run() {
                try {
                    while (lock.tryLock() == false) {
                        Thread.sleep(100 + RandomUtils.nextInt(100));
                    }/*from   w ww . j  a  v a 2 s. co  m*/

                    System.out.println("id: " + lock.getId() + " is leader: " + lock.isOwner());
                } catch (InterruptedException e) {
                    want.fail();
                } catch (KeeperException e) {
                    want.fail();
                } finally {
                    latch.countDown();
                    try {
                        lock.unlock();
                    } catch (KeeperException e) {
                        want.fail();
                    }
                }

            }
        });
    }

    try {
        latch.await();
    } catch (InterruptedException e) {
        want.fail();
    }

    exeucotr.shutdown();
}

From source file:com.ras.updater.Downloader.java

/**
 * This method will check for updates on all {@link #m_fileProviders} and download anything with an update.
 * @return true if at least one file was updated or false if no files were updated
 *//*from  w w  w .j a v  a 2  s  .c  om*/
public boolean update() {
    ArrayList<Future<Boolean>> results = new ArrayList<Future<Boolean>>();
    ExecutorService es = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    for (IFileProvider fileProvider : m_fileProviders) {
        FileUpdaterCallable task = new FileUpdaterCallable(fileProvider);
        results.add(es.submit(task));
    }
    es.shutdown();
    try {
        if (!es.awaitTermination(m_downloadTimeout, m_downloadTimeUnit))
            es.shutdownNow();
    } catch (InterruptedException e) {
        m_statusCallback.handleError(e);
        es.shutdownNow();
        Thread.currentThread().interrupt();
    }

    //Loop through the results for update values
    for (Future<Boolean> result : results) {
        try {
            if (result.isDone() && result.get() != null && result.get())
                return true;
        } catch (InterruptedException e) {
            //This should never happen
            m_statusCallback.handleError(e);
        } catch (ExecutionException e) {
            m_statusCallback.handleError(e);
        }
    }

    return false;
}

From source file:com.netflix.curator.framework.recipes.shared.TestSharedCount.java

@Test
public void testMultiClients() throws Exception {
    final int CLIENT_QTY = 5;

    List<Future<List<Integer>>> futures = Lists.newArrayList();
    final List<CuratorFramework> clients = new CopyOnWriteArrayList<CuratorFramework>();
    try {//from  w  w w  . j ava  2  s.co  m
        final CountDownLatch startLatch = new CountDownLatch(CLIENT_QTY);
        final Semaphore semaphore = new Semaphore(0);
        ExecutorService service = Executors
                .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("Test-%d").build());
        for (int i = 0; i < CLIENT_QTY; ++i) {
            Future<List<Integer>> future = service.submit(new Callable<List<Integer>>() {
                @Override
                public List<Integer> call() throws Exception {
                    final List<Integer> countList = Lists.newArrayList();
                    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                            new RetryOneTime(1));
                    clients.add(client);
                    client.start();

                    SharedCount count = new SharedCount(client, "/count", 10);

                    final CountDownLatch latch = new CountDownLatch(1);
                    count.addListener(new SharedCountListener() {
                        @Override
                        public void countHasChanged(SharedCountReader sharedCount, int newCount)
                                throws Exception {
                            if (newCount < 0) {
                                latch.countDown();
                            } else {
                                countList.add(newCount);
                            }

                            semaphore.release();
                        }

                        @Override
                        public void stateChanged(CuratorFramework client, ConnectionState newState) {
                        }
                    });
                    count.start();
                    startLatch.countDown();
                    latch.await();
                    return countList;
                }
            });
            futures.add(future);
        }

        CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(),
                new RetryOneTime(1));
        clients.add(client);
        client.start();

        Assert.assertTrue(startLatch.await(10, TimeUnit.SECONDS));

        SharedCount count = new SharedCount(client, "/count", 10);
        count.start();

        List<Integer> countList = Lists.newArrayList();
        Random random = new Random();
        for (int i = 0; i < 100; ++i) {
            Thread.sleep(random.nextInt(10));

            int next = random.nextInt(100);
            countList.add(next);
            count.setCount(next);

            Assert.assertTrue(semaphore.tryAcquire(CLIENT_QTY, 10, TimeUnit.SECONDS));
        }
        count.setCount(-1);

        for (Future<List<Integer>> future : futures) {
            List<Integer> thisCountList = future.get();
            Assert.assertEquals(thisCountList, countList);
        }
    } finally {
        for (CuratorFramework client : clients) {
            IOUtils.closeQuietly(client);
        }
    }
}

From source file:com.test.HibernateDerbyLockingTest.java

public void testJDBC() throws Exception {
    final DerbyTemplate template = new DerbyTemplate();
    try {/*ww w .  j a  va 2 s. c o m*/
        template.doWithStatement(new IStatementCallback() {
            public void execute(Statement statement) throws Exception {
                statement.execute(
                        "CREATE TABLE TEST(\n" + "ID CHAR(36) NOT NULL,\n" + "NAME VARCHAR(255)\n" + ")");
            }
        });
        template.doWithStatement(new IStatementCallback() {
            public void execute(Statement statement) throws Exception {
                statement.execute("INSERT INTO TEST(ID, NAME) VALUES('12345', 'Bob')");
            }
        });

        final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>();

        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<?> submit = executorService.submit(new Callable<Object>() {

            public Object call() throws Exception {
                template.doWithStatement(new IStatementCallback() {
                    public void execute(Statement statement) throws Exception {
                        ResultSet resultSet = statement.executeQuery(
                                "SELECT ID, NAME FROM TEST WHERE ID = '12345' for update with rs");
                        while (resultSet.next()) {
                            String id = resultSet.getString("ID");
                            String name = resultSet.getString("NAME");
                        }
                        try {
                            Thread.sleep(2000);
                        } catch (Throwable t) {
                        }
                        System.out.println("one");
                        queue.add("one");
                        try {
                            Thread.sleep(500);
                        } catch (Throwable t) {
                        }
                    }
                });
                return null;
            }
        });
        Thread.sleep(500);
        Future<?> submit2 = executorService.submit(new Callable<Object>() {
            public Object call() throws Exception {
                template.doWithStatement(new IStatementCallback() {
                    public void execute(Statement statement) throws Exception {
                        ResultSet resultSet = statement.executeQuery(
                                "SELECT ID, NAME FROM TEST WHERE ID = '12345' for update with rr");
                        while (resultSet.next()) {
                            String id = resultSet.getString("ID");
                            String name = resultSet.getString("NAME");
                        }
                        queue.add("two");
                        System.out.println("two");
                    }
                });
                return null;
            }
        });
        submit.get();
        submit2.get();
        assertEquals("one", queue.poll(3, TimeUnit.SECONDS));
        assertEquals("two", queue.poll(3, TimeUnit.SECONDS));
    } finally {
        template.doWithStatement(new IStatementCallback() {
            public void execute(Statement statement) throws Exception {
                statement.execute("DROP TABLE TEST");
            }
        });
    }
}