Example usage for java.util.concurrent ExecutorService execute

List of usage examples for java.util.concurrent ExecutorService execute

Introduction

In this page you can find the example usage for java.util.concurrent ExecutorService execute.

Prototype

void execute(Runnable command);

Source Link

Document

Executes the given command at some time in the future.

Usage

From source file:koper.kafka.KafkaBatchSenderTest.java

/**
 * ?10??/*from w  ww  .j  a va  2s  . com*/
 *   messageSender.send(topic2, msg) ???
 */
public void testInsertOrder() {

    int c = 100;
    int n = 10;
    for (int i = 0; i < c; i++) {

        ExecutorService executorService = Executors.newFixedThreadPool(16);

        int x = i;
        executorService.execute(new Runnable() {

            @Override
            public void run() {
                for (int j = 0; j < n; j++) {
                    Order order = newOrder(x * 10 + j);
                    String newOrderId = orderMapper.insertOrder(order);
                    System.out.println("****** insert Order  " + newOrderId);
                }

            }
        });
    }
}

From source file:org.waarp.openr66.protocol.http.rest.test.HttpTestRestR66Client.java

public static void launchThreads() {
    // init thread model
    ExecutorService pool = Executors.newFixedThreadPool(NB);
    HttpTestRestR66Client[] clients = new HttpTestRestR66Client[NB];
    for (int i = 0; i < NB; i++) {
        clients[i] = new HttpTestRestR66Client();
    }/*w  w w.j  a  v  a2 s.co m*/
    for (int i = 0; i < NB; i++) {
        pool.execute(clients[i]);
    }
    pool.shutdown();
    try {
        while (!pool.awaitTermination(100000, TimeUnit.SECONDS))
            ;
    } catch (InterruptedException e) {
    }
}

From source file:org.openhab.core.karaf.internal.FeatureInstaller.java

protected void modified(final Map<String, Object> config) {
    ExecutorService scheduler = Executors.newSingleThreadExecutor();
    scheduler.execute(new Runnable() {
        @Override/*  w  w  w . ja  v a  2s .c  o m*/
        public void run() {
            installPackage(config);

            // install addons
            for (String type : addonTypes) {
                Object install = config.get(type);
                if (install instanceof String) {
                    installFeatures(type, (String) install);
                }
            }
        }

    });
}

From source file:com.google.api.ads.adwords.jaxws.extensions.kratu.data.KratuProcessor.java

public void processKratus(Long topAccountId, Date dateStart, Date dateEnd) throws InterruptedException {
    System.out.println("Processing Kratus for" + topAccountId);

    // We use a Latch so the main thread knows when all the worker threads are complete.
    final CountDownLatch latch = new CountDownLatch(1);
    Stopwatch stopwatch = Stopwatch.createStarted();

    RunnableKratu runnableKratu = createRunnableKratu(topAccountId, storageHelper, dateStart, dateEnd);

    ExecutorService executorService = Executors.newFixedThreadPool(1);
    runnableKratu.setLatch(latch);//from  w  w  w. jav a 2s .  c  o  m
    executorService.execute(runnableKratu);

    latch.await();
    stopwatch.stop();
}

From source file:gridool.mapred.db.task.Dht2DBGatherReduceTask.java

@Override
protected void invokeShuffle(final ExecutorService shuffleExecPool, final ArrayQueue<DBRecord> queue) {
    shuffleExecPool.execute(new Runnable() {
        public void run() {
            String driverClassName = getDriverClassName();
            String connectUrl = getReduceOutputDestinationDbUrl();
            String mapOutputTableName = getReduceOutputTableName();
            String[] fieldNames = jobConf.getReduceOutputFieldNames();
            DBRecord[] records = queue.toArray(DBRecord.class);
            final DBInsertOperation ops = new DBInsertOperation(driverClassName, connectUrl, null,
                    mapOutputTableName, fieldNames, records);
            ops.setAuth(getUserName(), getPassword());
            try {
                ops.execute();/*from   w ww  . j  av  a2 s.co m*/
            } catch (SQLException sqle) {
                LogFactory.getLog(getClass()).error(sqle);
            } catch (GridException ge) {
                LogFactory.getLog(getClass()).error(ge);
            } catch (Throwable te) {
                LogFactory.getLog(getClass()).error(te);
            }
        }
    });
}

From source file:org.apache.activemq.leveldb.test.MasterLevelDBStoreTest.java

@Test(timeout = 1000 * 60 * 10)
public void testStoppingStoreStopsTransport() throws Exception {
    store = new MasterLevelDBStore();
    store.setReplicas(0);//from   ww w . j  ava  2 s  .c  om

    ExecutorService threads = Executors.newFixedThreadPool(1);
    threads.execute(new Runnable() {
        @Override
        public void run() {
            try {
                store.start();
            } catch (Exception e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }
    });

    // give some time to come up..
    Thread.sleep(2000);
    String address = store.transport_server().getBoundAddress();
    URI bindAddress = new URI(address);
    System.out.println(address);
    Socket socket = new Socket();
    try {
        socket.bind(new InetSocketAddress(bindAddress.getHost(), bindAddress.getPort()));
        fail("We should not have been able to connect...");
    } catch (BindException e) {
        System.out.println("Good. We cannot bind.");
    }

    threads.execute(new Runnable() {
        @Override
        public void run() {
            try {
                store.stop();
            } catch (Exception e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }
    });

    Thread.sleep(2000);
    try {
        socket.bind(new InetSocketAddress(bindAddress.getHost(), bindAddress.getPort()));
        System.out.println("Can bind, so protocol server must have been shut down.");

    } catch (IllegalStateException e) {
        fail("Server protocol port is still opened..");
    }

}

From source file:org.wso2.carbon.sample.kafka.performance.KafkaClient.java

private void start() {
    ExecutorService executor = Executors.newFixedThreadPool(noOfPublishers);
    for (int i = 0; i < noOfPublishers; i++) {
        executor.execute(new KafkaProducer());
    }//from w  w  w  .j  av  a2s . com
}

From source file:edu.lternet.pasta.dml.util.DocumentDownloadUtil.java

public InputStream downloadDocument(final String id, final EcogridEndPointInterface endpoint) throws Exception {

    init();//from w ww. j av  a 2 s  .co m

    log.debug("starting the download");

    ExecutorService service = Executors.newSingleThreadExecutor();
    service.execute(new Runnable() {
        public void run() {
            long startTime = System.currentTimeMillis();

            try {
                if (endpoint instanceof AuthenticatedEcogridEndPointInterface) {
                    AuthenticatedQueryServiceGetToStreamClient authenticatedEcogridClient = new AuthenticatedQueryServiceGetToStreamClient(
                            new URL(((AuthenticatedEcogridEndPointInterface) endpoint)
                                    .getMetacatAuthenticatedEcogridEndPoint()));
                    authenticatedEcogridClient.get(id,
                            ((AuthenticatedEcogridEndPointInterface) endpoint).getSessionId(), outputStream);
                } else {
                    QueryServiceGetToStreamClient ecogridClient = new QueryServiceGetToStreamClient(
                            new URL(endpoint.getMetacatEcogridEndPoint()));
                    ecogridClient.get(id, outputStream);
                }
                outputStream.close();

                long endTime = System.currentTimeMillis();
                log.debug((endTime - startTime) + " ms to download document data");

                log.debug("Done downloading id=" + id);

            } catch (Exception e) {
                log.error("Error getting document from ecogrid: " + e.getMessage());
                e.printStackTrace();
            }

        }
    });

    //wait for the download to complete
    service.shutdown();
    service.awaitTermination(0, TimeUnit.SECONDS);

    log.debug("done with the download");

    return inputStream;

}

From source file:org.onesec.core.provider.ProviderRegistryTest.java

@Test(timeOut = 180000)
public void test()
        throws InterruptedException, IOException, ProviderRegistryException, JtapiPeerUnavailableException {

    List<StateListenerConfiguration> listenersConfig = new ArrayList<StateListenerConfiguration>();
    listenersConfig.add(new StateListenerConfigurationImpl(new StateLogger(), null));

    StateListenersCoordinator listenersCoordinator = new StateListenersCoordinatorImpl(listenersConfig);

    final ProviderRegistry registry = new ProviderRegistryImpl(listenersCoordinator,
            LoggerFactory.getLogger(ProviderRegistry.class));

    final ProviderConfigurator configurator = new FileProviderConfigurator(
            new File(System.getProperty("user.home") + "/.onesec"),
            new ProviderConfiguratorListenersImpl(Arrays.asList((ProviderConfiguratorListener) registry)),
            LoggerFactory.getLogger(ProviderConfigurator.class));

    ProviderConfiguratorState state = configurator.getState();
    StateWaitResult res = state.waitForState(new int[] { ProviderConfiguratorState.CONFIGURATION_UPDATED },
            1000L);/*w w w.j  av  a 2  s . co m*/

    assertFalse(res.isWaitInterrupted());

    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(new Runnable() {
        public void run() {
            try {
                boolean allControllersInService = false;
                while (!allControllersInService) {
                    allControllersInService = true;
                    for (ProviderController controller : registry.getProviderControllers())
                        if (controller.getState().getId() != ProviderControllerState.IN_SERVICE) {
                            allControllersInService = false;
                            break;
                        }
                    TimeUnit.SECONDS.sleep(1);
                }
            } catch (InterruptedException e) {

            }
        }
    });

    executor.shutdown();
    executor.awaitTermination(175, TimeUnit.SECONDS);

    List<String> numbers = FileUtils
            .readLines(new File(System.getProperty("user.home") + "/" + "/.onesec/numbers.txt"));

    for (String number : numbers) {
        ProviderController controller = registry.getProviderController(number);
        assertNotNull(controller);
        int intNumber = Integer.valueOf(number);
        assertTrue(intNumber >= controller.getFromNumber());
        assertTrue(intNumber <= controller.getToNumber());
    }

    registry.shutdown();
}

From source file:org.globus.gsi.jsse.SSLConfiguratorTest.java

private SSLServerSocket startServer(SSLConfigurator config)
        throws GlobusSSLConfigurationException, IOException {
    SSLServerSocketFactory sslserversocketfactory = config.createServerFactory();
    final SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(9991);

    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(new Runnable() {
        /**/*from www  . ja va 2  s . c o m*/
         * When an object implementing interface <code>Runnable</code> is
         * used to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p/>
         * The general contract of the method <code>run</code> is that it
         * may take any action whatsoever.
         *
         * @see Thread#run()
         */
        public void run() {
            latch.countDown();
            try {
                SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();
                InputStream inputstream = sslsocket.getInputStream();
                InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
                BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
                String line;
                while ((line = bufferedreader.readLine()) != null) {
                    builder.append(line);
                }
                assertEquals(builder.toString().trim(), "hello");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    return sslserversocket;
}