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:org.kurento.test.metatest.BrowserCreationTest.java

private void createParallelBrowsers(int numBrowsers) throws InterruptedException {
    long startTime = System.currentTimeMillis();

    final List<Browser> browsers = Collections.synchronizedList(new ArrayList<Browser>());

    ExecutorService executor = Executors.newFixedThreadPool(numBrowsers);

    try {//from w  w  w.  j  a v  a2s.c  om

        final AbortableCountDownLatch latch = new AbortableCountDownLatch(numBrowsers);

        for (int i = 0; i < numBrowsers; i++) {

            final int numBrowser = i;

            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {

                        Browser browser = new Browser.Builder().scope(BrowserScope.DOCKER).build();

                        browsers.add(browser);

                        browser.setId("browser" + numBrowser);

                        browser.init();

                        latch.countDown();

                    } catch (Throwable t) {
                        latch.abort("Exception setting up test. A browser could not be initialised", t);
                    }
                }
            });
        }

        latch.await();

        long creationTime = System.currentTimeMillis() - startTime;

        log.debug("----------------------------------------------------------------");

        log.debug("All {} browsers started in {} millis", numBrowsers, creationTime);

        log.debug("----------------------------------------------------------------");

    } finally {

        log.debug("***************************************************************");

        startTime = System.currentTimeMillis();

        final AbortableCountDownLatch latch = new AbortableCountDownLatch(numBrowsers);

        for (final Browser browser : browsers) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    browser.close();
                    latch.countDown();
                }
            });
        }

        executor.shutdown();
        executor.awaitTermination(10, TimeUnit.HOURS);

        latch.await();

        long destructionTime = System.currentTimeMillis() - startTime;

        log.debug("----------------------------------------------------------------");

        log.debug("All {} browsers stopped in {} millis", numBrowsers, destructionTime);

        log.debug("----------------------------------------------------------------");
    }
}

From source file:com.test.test.ClientServerTest.java

@Test
public void testMutliThreaded() throws Exception {

    // Number of threads
    final int size = 10;

    LOG.debug("clientSimple1:" + clientSimple);

    IServiceSimple proxyService = clientSimple.getProxy(IServiceSimple.class);
    LOG.debug("proxyService:" + proxyService);

    List<ClientCallable> clientCallableList = new ArrayList<ClientCallable>();

    for (int i = 0; i < size; i++) {
        clientCallableList.add(new ClientCallable(proxyService, i));
    }/*from  w  ww.ja v  a 2s.c o  m*/

    List<FutureTask<String>> futureTaskList = new ArrayList<FutureTask<String>>();
    for (ClientCallable clientCallable : clientCallableList) {
        futureTaskList.add(new FutureTask<String>(clientCallable));
    }

    long beginTime = System.currentTimeMillis();
    ExecutorService executor = Executors.newFixedThreadPool(futureTaskList.size());
    for (FutureTask<String> futureTask : futureTaskList) {
        executor.execute(futureTask);
    }

    boolean ready = false;
    int[] dones = new int[futureTaskList.size()];
    String[] writes = new String[futureTaskList.size()];

    int indexValue = 0;
    while (!ready) {

        int count = 0;
        indexValue = 0;
        for (FutureTask<String> futureTask : futureTaskList) {
            if (futureTask.isDone() & dones[indexValue] == 0) {
                writes[indexValue] = futureTask.get();
                dones[indexValue] = 1;
            }
            indexValue++;
        }

        for (int k = 0; k < dones.length; k++) {
            if (dones[k] == 1) {
                count++;
            }
        }

        if (count == futureTaskList.size()) {
            ready = true;
        }

        //            Thread.sleep(500);
    }

    LOG.debug("\n\n\n ====== DONE ====== ");
    LOG.debug("  time:" + (System.currentTimeMillis() - beginTime) + "ms\n\n");
    executor.shutdown();

    for (int i = 0; i < writes.length; i++) {
        LOG.debug("- " + writes[i]);
    }
    LOG.debug("\n\n\n ====== DONE ====== \n\n");
}

From source file:edu.cmu.cs.lti.ark.fn.identification.latentmodel.LatentAlphabetCreationThreaded.java

/**
 * Splits frameElementLines into numThreads equally-sized batches and creates an alphabet
 * file for each one./* w w  w  .  ja  v  a2  s .co  m*/
 *
 * @throws java.io.IOException
 */
public void createLocalAlphabets() throws IOException {
    final List<String> frameLines = Files.readLines(new File(frameElementsFile), Charsets.UTF_8)
            .subList(startIndex, endIndex);
    final List<String> parseLines = Files.readLines(new File(parseFile), Charsets.UTF_8);

    final ExecutorService threadPool = newFixedThreadPool(numThreads);
    int i = 0;
    for (int start = startIndex; start < endIndex; start += BATCH_SIZE) {
        final int threadId = i;
        final List<String> frameLineBatch = frameLines.subList(start,
                Math.min(frameLines.size(), start + BATCH_SIZE));
        threadPool.execute(new Runnable() {
            public void run() {
                logger.info("Thread " + threadId + " : start");
                processBatch(threadId, frameLineBatch, parseLines);
                logger.info("Thread " + threadId + " : end");
            }
        });
        i++;
    }
    threadPool.shutdown();
}

From source file:ca.etsmtl.applets.etsmobile.service.RegistrationIntentService.java

/**
 * Persist registration to third-party servers.
 * <p/>/*from w w w.  ja v a  2  s . c o m*/
 * Modify this method to associate the user's GCM registration token with any server-side account
 * maintained by your application.
 *
 * @param token The new token.
 */
private void sendRegistrationToServer(String token) {
    // Add custom implementation, as needed.
    ExecutorService executor = Executors.newFixedThreadPool(1);
    CreateEndpointJob worker = new CreateEndpointJob(getApplicationContext());

    //TODO put application ARN in a property file
    worker.setThreadProperties(token,
            ApplicationManager.domaine + "\\" + ApplicationManager.userCredentials.getUsername(),
            getString(R.string.aws_application_arn));
    worker.run();
    executor.execute(worker);
}

From source file:org.orekit.time.UTCScaleTest.java

@Test
public void testMultithreading() {

    // generate reference offsets using a single thread
    RandomGenerator random = new Well1024a(6392073424l);
    List<AbsoluteDate> datesList = new ArrayList<AbsoluteDate>();
    List<Double> offsetsList = new ArrayList<Double>();
    AbsoluteDate reference = utc.getFirstKnownLeapSecond().shiftedBy(-Constants.JULIAN_YEAR);
    double testRange = utc.getLastKnownLeapSecond().durationFrom(reference) + Constants.JULIAN_YEAR;
    for (int i = 0; i < 10000; ++i) {
        AbsoluteDate randomDate = reference.shiftedBy(random.nextDouble() * testRange);
        datesList.add(randomDate);//from   w  w w  .  j  a  v a  2s  . c  om
        offsetsList.add(utc.offsetFromTAI(randomDate));
    }

    // check the offsets in multi-threaded mode
    ExecutorService executorService = Executors.newFixedThreadPool(100);

    for (int i = 0; i < datesList.size(); ++i) {
        final AbsoluteDate date = datesList.get(i);
        final double offset = offsetsList.get(i);
        executorService.execute(new Runnable() {
            public void run() {
                Assert.assertEquals(offset, utc.offsetFromTAI(date), 1.0e-12);
            }
        });
    }

    try {
        executorService.shutdown();
        executorService.awaitTermination(3, TimeUnit.SECONDS);
    } catch (InterruptedException ie) {
        Assert.fail(ie.getLocalizedMessage());
    }

}

From source file:mamo.vanillaVotifier.VotifierServer.java

public synchronized void start() throws IOException {
    if (isRunning()) {
        throw new IllegalStateException("Server is already running!");
    }//from  w  w w . j  a v a 2s  .  c om
    notifyListeners(new ServerStartingEvent());
    serverSocket = new ServerSocket();
    serverSocket.bind(votifier.getConfig().getInetSocketAddress());
    running = true;
    notifyListeners(new ServerStartedEvent());
    new Thread(new Runnable() {
        @Override
        public void run() {
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            while (isRunning()) {
                try {
                    final Socket socket = serverSocket.accept();
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                notifyListeners(new ConnectionEstablishedEvent(socket));
                                socket.setSoTimeout(SocketOptions.SO_TIMEOUT); // SocketException: handled by try/catch.
                                BufferedWriter writer = new BufferedWriter(
                                        new OutputStreamWriter(socket.getOutputStream()));
                                writer.write("VOTIFIER 2.9\n");
                                writer.flush();
                                BufferedInputStream in = new BufferedInputStream(socket.getInputStream()); // IOException: handled by try/catch.
                                byte[] request = new byte[((RSAPublicKey) votifier.getConfig().getKeyPair()
                                        .getPublic()).getModulus().bitLength() / Byte.SIZE];
                                in.read(request); // IOException: handled by try/catch.
                                notifyListeners(new EncryptedInputReceivedEvent(socket, new String(request)));
                                request = RsaUtils
                                        .getDecryptCipher(votifier.getConfig().getKeyPair().getPrivate())
                                        .doFinal(request); // IllegalBlockSizeException: can't happen.
                                String requestString = new String(request);
                                notifyListeners(new DecryptedInputReceivedEvent(socket, requestString));
                                String[] requestArray = requestString.split("\n");
                                if ((requestArray.length == 5 || requestArray.length == 6)
                                        && requestArray[0].equals("VOTE")) {
                                    notifyListeners(new VoteEventVotifier(socket, new Vote(requestArray[1],
                                            requestArray[2], requestArray[3], requestArray[4])));
                                    for (VoteAction voteAction : votifier.getConfig().getVoteActions()) {
                                        String[] params = new String[4];
                                        try {
                                            for (int i = 0; i < params.length; i++) {
                                                params[i] = SubstitutionUtils.applyRegexReplacements(
                                                        requestArray[i + 1], voteAction.getRegexReplacements());
                                            }
                                        } catch (PatternSyntaxException e) {
                                            notifyListeners(new RegularExpressionPatternErrorException(e));
                                            params = new String[] { requestArray[1], requestArray[2],
                                                    requestArray[3], requestArray[4] };
                                        }
                                        if (voteAction.getCommandSender() instanceof RconCommandSender) {
                                            RconCommandSender commandSender = (RconCommandSender) voteAction
                                                    .getCommandSender();
                                            StrSubstitutor substitutor = SubstitutionUtils.buildStrSubstitutor(
                                                    new SimpleEntry<String, Object>("service-name", params[0]),
                                                    new SimpleEntry<String, Object>("user-name", params[1]),
                                                    new SimpleEntry<String, Object>("address", params[2]),
                                                    new SimpleEntry<String, Object>("timestamp", params[3]));
                                            for (String command : voteAction.getCommands()) {
                                                String theCommand = substitutor.replace(command);
                                                notifyListeners(new SendingRconCommandEvent(
                                                        commandSender.getRconConnection(), theCommand));
                                                try {
                                                    notifyListeners(new RconCommandResponseEvent(
                                                            commandSender.getRconConnection(), commandSender
                                                                    .sendCommand(theCommand).getPayload()));
                                                } catch (Exception e) {
                                                    notifyListeners(new RconExceptionEvent(
                                                            commandSender.getRconConnection(), e));
                                                }
                                            }
                                        }
                                        if (voteAction.getCommandSender() instanceof ShellCommandSender) {
                                            ShellCommandSender commandSender = (ShellCommandSender) voteAction
                                                    .getCommandSender();
                                            HashMap<String, String> environment = new HashMap<String, String>();
                                            environment.put("voteServiceName", params[0]);
                                            environment.put("voteUserName", params[1]);
                                            environment.put("voteAddress", params[2]);
                                            environment.put("voteTimestamp", params[3]);
                                            for (String command : voteAction.getCommands()) {
                                                notifyListeners(new SendingShellCommandEvent(command));
                                                try {
                                                    commandSender.sendCommand(command, environment);
                                                    notifyListeners(new ShellCommandSentEvent());
                                                } catch (Exception e) {
                                                    notifyListeners(new ShellCommandExceptionEvent(e));
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    notifyListeners(new InvalidRequestEvent(socket, requestString));
                                }
                            } catch (SocketTimeoutException e) {
                                notifyListeners(new ReadTimedOutExceptionEvent(socket, e));
                            } catch (BadPaddingException e) {
                                notifyListeners(new DecryptInputExceptionEvent(socket, e));
                            } catch (Exception e) {
                                notifyListeners(new CommunicationExceptionEvent(socket, e));
                            }
                            try {
                                socket.close();
                                notifyListeners(new ConnectionClosedEvent(socket));
                            } catch (Exception e) { // IOException: catching just in case. Continue even if socket doesn't close.
                                notifyListeners(new ConnectionCloseExceptionEvent(socket, e));
                            }
                        }
                    });
                } catch (Exception e) {
                    if (running) { // Show errors only while running, to hide error while stopping.
                        notifyListeners(new ConnectionEstablishExceptionEvent(e));
                    }
                }
            }
            executorService.shutdown();
            if (!executorService.isTerminated()) {
                notifyListeners(new ServerAwaitingTaskCompletionEvent());
                try {
                    executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
                } catch (Exception e) {
                    // InterruptedException: can't happen.
                }
            }
            notifyListeners(new ServerStoppedEvent());
        }
    }).start();
}

From source file:org.nebula.framework.core.NodeWorker.java

private void heartbeat(ExecutorService heartbeatExecutor, String registrationId) {

    HeartbeatWorker heartbeatWorker = new HeartbeatWorker(nebulaClient, configuration.getHeartbeatInSeconds(),
            registrationId);/*www  .  j a v a 2s  .  c  om*/

    //Use the configuration from server before the WorkflowWorker start
    heartbeatWorker.runOnce();

    heartbeatExecutor.execute(heartbeatWorker);

}

From source file:com.test.test.ClientServerTest.java

@Test
public void testMutliThreadProxyClient() throws Exception {

    // Number of threads
    final int size = 20;

    LOG.debug("clientSimple1:" + clientSimple);

    List<IServiceSimple> serviceSimpleList = new ArrayList<IServiceSimple>();
    for (int i = 0; i < size; i++) {
        IServiceSimple proxyService = clientSimple.getProxy(IServiceSimple.class);
        LOG.debug("proxyService:" + proxyService);
        serviceSimpleList.add(proxyService);
    }/*  ww  w .  j a v  a2  s . c om*/

    List<ClientCallable> clientCallableList = new ArrayList<ClientCallable>();

    for (int i = 0; i < size; i++) {
        clientCallableList.add(new ClientCallable(serviceSimpleList.get(i), i));
    }

    List<FutureTask<String>> futureTaskList = new ArrayList<FutureTask<String>>();
    for (ClientCallable clientCallable : clientCallableList) {
        futureTaskList.add(new FutureTask<String>(clientCallable));
    }

    long beginTime = System.currentTimeMillis();
    ExecutorService executor = Executors.newFixedThreadPool(futureTaskList.size());
    for (FutureTask<String> futureTask : futureTaskList) {
        executor.execute(futureTask);
    }

    boolean ready = false;
    int[] dones = new int[futureTaskList.size()];
    String[] writes = new String[futureTaskList.size()];

    int indexValue = 0;
    while (!ready) {

        int count = 0;
        indexValue = 0;
        for (FutureTask<String> futureTask : futureTaskList) {
            if (futureTask.isDone() & dones[indexValue] == 0) {
                writes[indexValue] = futureTask.get();
                dones[indexValue] = 1;
            }
            indexValue++;
        }

        for (int k = 0; k < dones.length; k++) {
            if (dones[k] == 1) {
                count++;
            }
        }

        if (count == futureTaskList.size()) {
            ready = true;
        }

        //            Thread.sleep(500);
    }

    LOG.debug("\n\n\n ====== DONE ====== ");
    LOG.debug("  time:" + (System.currentTimeMillis() - beginTime) + "ms\n\n");
    executor.shutdown();

    for (int i = 0; i < writes.length; i++) {
        LOG.debug("- " + writes[i]);
    }
    LOG.debug("\n\n\n ====== DONE ====== \n\n");

    Thread.sleep(20000);
    LOG.debug("\n\n\n\n+++++++++++++++++++++++++");
    LOG.debug("New system:");
    IServiceSimple proxyService2 = clientSimple.getProxy(IServiceSimple.class);
    proxyService2.functionNumber1("1", "1");

}

From source file:org.apache.solr.client.solrj.impl.ConcurrentUpdateSolrClientTest.java

@Test
public void testConcurrentCollectionUpdate() throws Exception {

    int cussThreadCount = 2;
    int cussQueueSize = 100;
    int numDocs = 100;
    int numRunnables = 5;
    int expected = numDocs * numRunnables;

    try (ConcurrentUpdateSolrClient concurrentClient = new ConcurrentUpdateSolrClient(
            jetty.getBaseUrl().toString(), cussQueueSize, cussThreadCount)) {
        concurrentClient.setPollQueueTime(0);

        // ensure it doesn't block where there's nothing to do yet
        concurrentClient.blockUntilFinished();

        // Delete all existing documents.
        concurrentClient.deleteByQuery("collection1", "*:*");

        int poolSize = 5;
        ExecutorService threadPool = ExecutorUtil.newMDCAwareFixedThreadPool(poolSize,
                new SolrjNamedThreadFactory("testCUSS"));

        for (int r = 0; r < numRunnables; r++)
            threadPool
                    .execute(new SendDocsRunnable(String.valueOf(r), numDocs, concurrentClient, "collection1"));

        // ensure all docs are sent
        threadPool.awaitTermination(5, TimeUnit.SECONDS);
        threadPool.shutdown();// w ww . ja  va  2s  .c o m

        concurrentClient.commit("collection1");

        assertEquals(expected,
                concurrentClient.query("collection1", new SolrQuery("*:*")).getResults().getNumFound());

        // wait until all requests are processed by CUSS 
        concurrentClient.blockUntilFinished();
        concurrentClient.shutdownNow();
    }

    try (ConcurrentUpdateSolrClient concurrentClient = new ConcurrentUpdateSolrClient(
            jetty.getBaseUrl().toString() + "/collection1", cussQueueSize, cussThreadCount)) {
        assertEquals(expected, concurrentClient.query(new SolrQuery("*:*")).getResults().getNumFound());
    }

}

From source file:info.archinnov.achilles.embedded.ServerStarter.java

private void start(final TypedMap parameters) {
    if (isAlreadyRunning()) {
        log.debug("Cassandra is already running, not starting new one");
        return;/*from   ww w.  j  a v a2 s . c  o  m*/
    }

    final String triggersDir = createTriggersFolder();

    log.info(" Random embedded Cassandra RPC port/Thrift port = {}",
            parameters.<Integer>getTyped(CASSANDRA_THRIFT_PORT));
    log.info(" Random embedded Cassandra Native port/CQL port = {}",
            parameters.<Integer>getTyped(CASSANDRA_CQL_PORT));
    log.info(" Random embedded Cassandra Storage port = {}",
            parameters.<Integer>getTyped(CASSANDRA_STORAGE_PORT));
    log.info(" Random embedded Cassandra Storage SSL port = {}",
            parameters.<Integer>getTyped(CASSANDRA_STORAGE_SSL_PORT));
    log.info(" Random embedded Cassandra Remote JMX port = {}",
            System.getProperty("com.sun.management.jmxremote.port", "null"));
    log.info(" Embedded Cassandra triggers directory = {}", triggersDir);

    log.info("Starting Cassandra...");

    System.setProperty("cassandra.triggers_dir", triggersDir);
    System.setProperty("cassandra-foreground", "true");
    System.setProperty("cassandra.embedded.concurrent.reads",
            parameters.getTypedOr(CASSANDRA_CONCURRENT_READS, 32).toString());
    System.setProperty("cassandra.embedded.concurrent.writes",
            parameters.getTypedOr(CASSANDRA_CONCURRENT_WRITES, 32).toString());
    System.setProperty("cassandra-foreground", "true");

    final boolean useUnsafeCassandra = parameters.getTyped(USE_UNSAFE_CASSANDRA_DAEMON);

    if (useUnsafeCassandra) {
        System.setProperty("cassandra-num-tokens", "1");
    }

    System.setProperty("cassandra.config.loader", "info.archinnov.achilles.embedded.AchillesCassandraConfig");

    final CountDownLatch startupLatch = new CountDownLatch(1);
    final ExecutorService executor = Executors.newSingleThreadExecutor();
    final AtomicReference<CassandraDaemon> daemonRef = new AtomicReference<>();
    executor.execute(() -> {
        if (useUnsafeCassandra) {
            LOGGER.warn(
                    "******* WARNING, starting unsafe embedded Cassandra deamon. This should be only used for unit testing or development and not for production !");
        }

        CassandraDaemon cassandraDaemon = useUnsafeCassandra == true ? new AchillesCassandraDaemon()
                : new CassandraDaemon();

        cassandraDaemon.completeSetup();
        cassandraDaemon.activate();
        daemonRef.getAndSet(cassandraDaemon);
        startupLatch.countDown();
    });

    try {
        startupLatch.await(30, SECONDS);
    } catch (InterruptedException e) {
        log.error("Timeout starting Cassandra embedded", e);
        throw new IllegalStateException("Timeout starting Cassandra embedded", e);
    }

    // Generate an OrderedShutdownHook to shutdown all connections from java clients before closing the server
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            log.info("Calling stop on Embedded Cassandra server");
            daemonRef.get().stop();

            log.info("Calling shutdown on all Cluster instances");
            // First call shutdown on all registered Java driver Cluster instances
            orderedShutdownHook.callShutDown();

            log.info("Shutting down embedded Cassandra server");
            // Then shutdown the server
            executor.shutdownNow();
        }
    });
}