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:pt.webdetails.cdc.core.CoreHazelcastConfigHelper.java

/**
 * Sets MapConfig in Member/*from  w w  w . j  a  va2  s.  c  o m*/
 *
 * @param mapConfig the map configuration to send
 * @param member
 * @return
 * @throws InterruptedException
 */
public static Boolean spreadMapConfig(MapConfig mapConfig, Member member) {
    DistributedTask<Boolean> distribMapConfig = new DistributedTask<Boolean>(
            new DistributedMapConfig(mapConfig), member);
    ExecutorService execService = HazelcastManager.INSTANCE.getHazelcast().getExecutorService();
    execService.execute(distribMapConfig);
    try {
        return distribMapConfig.get();
    } catch (Exception e) {
        logger.error("Error attempting to send MapConfig " + mapConfig.getName() + " to " + member.toString());
        return false;
    }
}

From source file:pt.webdetails.cdc.ws.HazelcastMonitorService.java

private static LocalMapStats getLocalMapStats(Member member, String mapName)
        throws InterruptedException, ExecutionException {

    DistributedTask<MemberMapStat> mapStatTask = new DistributedTask<MemberMapStat>(
            new DistributedMapStatsCallable(mapName), member);

    ExecutorService execService = HazelcastManager.INSTANCE.getHazelcast().getExecutorService();
    execService.execute(mapStatTask);

    MemberMapStat mapStat = mapStatTask.get();
    return mapStat.getLocalMapStats();
}

From source file:pt.webdetails.cdc.ws.HazelcastMonitorService.java

private static DistributedMemberInfoCallable.MemberInfo getMemberInfo(Member member) {
    DistributedTask<DistributedMemberInfoCallable.MemberInfo> runtimeInfoTask = new DistributedTask<DistributedMemberInfoCallable.MemberInfo>(
            new DistributedMemberInfoCallable(), member);
    ExecutorService execService = HazelcastManager.INSTANCE.getHazelcast().getExecutorService();
    execService.execute(runtimeInfoTask);
    try {//from  w w w  .java  2s  .  c  o  m
        return runtimeInfoTask.get();
    } catch (InterruptedException e) {
        logger.error("Timeout waiting for LocalMapStats on member " + member.getInetSocketAddress(), e);
    } catch (ExecutionException e) {
        logger.error("Error waiting for LocalMapStats on member " + member.getInetSocketAddress(), e);
    }

    return null;
}

From source file:org.paxml.launch.PaxmlRunner.java

/**
 * Run the computed launch model with thread pool. It will run with default
 * 4 threads if not specifically specified in the launch model.
 * //from w ww.java 2  s .  c o  m
 * @param model
 *            the model containing the launch points
 */
public static void run(LaunchModel model, long executionId) {

    List<LaunchPoint> points = model.getLaunchPoints(false, executionId);
    if (log.isInfoEnabled()) {
        log.info("Found " + points.size() + " Paxml files to execute based on plan file: "
                + model.getPlanEntity().getResource().getPath());
    }
    if (points.isEmpty()) {
        return;
    }
    final int poolSize = model.getConcurrency() <= 0 ? Math.min(DEFAULT_CONCURRENCY, points.size())
            : model.getConcurrency();
    ExecutorService pool = Executors.newFixedThreadPool(poolSize);
    for (final LaunchPoint point : points) {
        pool.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    Context.cleanCurrentThreadContext();

                    logExecution(point.getResource(), true);

                    point.execute();
                } catch (Throwable t) {
                    if (log.isErrorEnabled()) {
                        log.error(findMessage(t), t);
                    }
                } finally {
                    logExecution(point.getResource(), false);
                }
            }

        });
    }

    try {
        pool.shutdown();
        // wait forever in a loop
        while (!pool.awaitTermination(1, TimeUnit.MINUTES)) {
            if (log.isDebugEnabled()) {
                log.debug("Waiting for all executors to finish...");
            }
        }

    } catch (InterruptedException e) {
        throw new PaxmlRuntimeException("Cannot wait for all executors to finish", e);
    } finally {
        pool.shutdownNow();
    }

}

From source file:org.semarglproject.rdf.rdfa.RdfaTestBundle.java

public static void downloadAllTests(int parallelism) throws InterruptedException {
    ExecutorService executorService = Executors.newFixedThreadPool(parallelism);
    executorService.execute(new TestDownloadWorker("rdfa1.0", "xhtml1"));
    executorService.execute(new TestDownloadWorker("rdfa1.0", "svg"));
    executorService.execute(new TestDownloadWorker("rdfa1.1", "html4"));
    executorService.execute(new TestDownloadWorker("rdfa1.1", "xhtml1"));
    executorService.execute(new TestDownloadWorker("rdfa1.1", "html5"));
    executorService.execute(new TestDownloadWorker("rdfa1.1", "xml"));
    executorService.execute(new TestDownloadWorker("rdfa1.1", "svg"));
    executorService.shutdown();/*from   w  w w  .  j  a  v a2s .c  o  m*/
    executorService.awaitTermination(10, TimeUnit.MINUTES);
}

From source file:com.ning.metrics.collector.TestPerformance.java

private static long scheduleScribeAgents() throws InterruptedException {
    ExecutorService e = Executors.newFixedThreadPool(THREADPOOL_SIZE,
            new NamedThreadFactory("Performance tests (Scribe client)"));

    long startTime = System.currentTimeMillis();
    for (int i = 0; i < NUMBER_OF_SCRIBE_CLIENTS; i++) {
        e.execute(new ScribeClient());
        log.debug(String.format("Thread %d/%d submitted", i + 1, NUMBER_OF_SCRIBE_CLIENTS));
    }/*from w ww . j  a  va2 s .  c  o m*/

    e.shutdown();
    e.awaitTermination(10, TimeUnit.MINUTES);
    return startTime;
}

From source file:com.app.util.SearchResultUtil.java

public static void performSearch() throws DatabaseConnectionException, SQLException {

    long startTime = System.nanoTime();

    ExecutorService executor = Executors.newFixedThreadPool(_THREAD_POOL_SIZE);

    List<Integer> userIds = UserUtil.getUserIds(true);

    for (int userId : userIds) {
        SearchResultRunnable searchResultRunnable = new SearchResultRunnable(userId);

        executor.execute(searchResultRunnable);
    }/*ww  w .  ja v  a2  s .c o  m*/

    executor.shutdown();

    try {
        executor.awaitTermination(_THREAD_TIMEOUT_SECONDS, TimeUnit.SECONDS);
    } catch (InterruptedException ie) {
        _log.error("The executor encountered an exception", ie);
    }

    long endTime = System.nanoTime();

    _log.info("Performing searches for {} users took {} milliseconds", userIds.size(),
            (endTime - startTime) / 1000000);
}

From source file:org.metaeffekt.dcc.agent.DccAgentTest.java

private static void startAgent() {

    agent = new DccAgent(port);

    ExecutorService executorService = Executors.newSingleThreadExecutor();

    final long begin = System.currentTimeMillis();

    executorService.execute(new Runnable() {

        @Override//ww  w  . j a va2  s. co m
        public void run() {
            try {
                agent.start();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    });

    LOG.info("Waiting for agent to start");
    while (!agent.isStarted()) {

        if (System.currentTimeMillis() - begin > STARTUP_TIMEOUT) {
            throw new IllegalStateException("Failed to start agent. Timeout expired.");
        }

        try {
            Thread.sleep(500);
            LOG.info(".");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    LOG.info("");
    LOG.info("Agent is started");
}

From source file:com.amazon.janusgraph.example.MarvelGraphFactory.java

public static void load(final JanusGraph graph, final int rowsToLoad, final boolean report) throws Exception {

    JanusGraphManagement mgmt = graph.openManagement();
    if (mgmt.getGraphIndex(CHARACTER) == null) {
        final PropertyKey characterKey = mgmt.makePropertyKey(CHARACTER).dataType(String.class).make();
        mgmt.buildIndex(CHARACTER, Vertex.class).addKey(characterKey).unique().buildCompositeIndex();
    }// ww  w. j a  v  a  2s.  co m
    if (mgmt.getGraphIndex(COMIC_BOOK) == null) {
        final PropertyKey comicBookKey = mgmt.makePropertyKey(COMIC_BOOK).dataType(String.class).make();
        mgmt.buildIndex(COMIC_BOOK, Vertex.class).addKey(comicBookKey).unique().buildCompositeIndex();
        mgmt.makePropertyKey(WEAPON).dataType(String.class).make();
        mgmt.makeEdgeLabel(APPEARED).multiplicity(Multiplicity.MULTI).make();
    }
    mgmt.commit();

    ClassLoader classLoader = MarvelGraphFactory.class.getClassLoader();
    URL resource = classLoader.getResource("META-INF/marvel.csv");
    int line = 0;
    Map<String, Set<String>> comicToCharacter = new HashMap<>();
    Map<String, Set<String>> characterToComic = new HashMap<>();
    Set<String> characters = new HashSet<>();
    BlockingQueue<Runnable> creationQueue = new LinkedBlockingQueue<>();
    try (CSVReader reader = new CSVReader(new InputStreamReader(resource.openStream()))) {
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null && line < rowsToLoad) {
            line++;
            String comicBook = nextLine[1];
            String[] characterNames = nextLine[0].split("/");
            if (!comicToCharacter.containsKey(comicBook)) {
                comicToCharacter.put(comicBook, new HashSet<String>());
            }
            List<String> comicCharacters = Arrays.asList(characterNames);
            comicToCharacter.get(comicBook).addAll(comicCharacters);
            characters.addAll(comicCharacters);

        }
    }

    for (String character : characters) {
        creationQueue.add(new CharacterCreationCommand(character, graph));
    }

    BlockingQueue<Runnable> appearedQueue = new LinkedBlockingQueue<>();
    for (String comicBook : comicToCharacter.keySet()) {
        creationQueue.add(new ComicBookCreationCommand(comicBook, graph));
        Set<String> comicCharacters = comicToCharacter.get(comicBook);
        for (String character : comicCharacters) {
            AppearedCommand lineCommand = new AppearedCommand(graph, new Appeared(character, comicBook));
            appearedQueue.add(lineCommand);
            if (!characterToComic.containsKey(character)) {
                characterToComic.put(character, new HashSet<String>());
            }
            characterToComic.get(character).add(comicBook);
        }
        REGISTRY.histogram("histogram.comic-to-character").update(comicCharacters.size());
    }

    int maxAppearances = 0;
    String maxCharacter = "";
    for (String character : characterToComic.keySet()) {
        Set<String> comicBookSet = characterToComic.get(character);
        int numberOfAppearances = comicBookSet.size();
        REGISTRY.histogram("histogram.character-to-comic").update(numberOfAppearances);
        if (numberOfAppearances > maxAppearances) {
            maxCharacter = character;
            maxAppearances = numberOfAppearances;
        }
    }
    LOG.info("Character {} has most appearances at {}", maxCharacter, maxAppearances);

    ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
    for (int i = 0; i < POOL_SIZE; i++) {
        executor.execute(new BatchCommand(graph, creationQueue));
    }
    executor.shutdown();
    while (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        LOG.info("Awaiting:" + creationQueue.size());
        if (report) {
            REPORTER.report();
        }
    }

    executor = Executors.newSingleThreadExecutor();
    executor.execute(new BatchCommand(graph, appearedQueue));

    executor.shutdown();
    while (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
        LOG.info("Awaiting:" + appearedQueue.size());
        if (report) {
            REPORTER.report();
        }
    }
    LOG.info("MarvelGraphFactory.load complete");
}

From source file:org.orbisgis.chart.ChartFactory.java

/**
 * Build a chart element/* ww  w.  j  a v a  2 s.c  om*/
 * 
 * @param chart 
 */
public static void buildChartElement(ChartElement chart) {
    BundleContext thisBundle = FrameworkUtil.getBundle(ChartFactory.class).getBundleContext();

    ExecutorService executorService = getExecutorService(thisBundle);
    CreateJFreeChart loadCategoryDataset = new CreateJFreeChart(chart, thisBundle);

    if (executorService != null) {
        executorService.execute(loadCategoryDataset);
    } else {
        loadCategoryDataset.execute();
    }
}