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:com.techcavern.pircbotz.hooks.managers.ThreadedListenerManager.java

protected void submitEvent(ExecutorService pool, final Listener<B> listener, final Event<B> event) {
    pool.execute(new ManagedFutureTask(listener, event, new Callable<Void>() {
        public Void call() {
            try {
                if (event.getBot() != null)
                    Utils.addBotToMDC(event.getBot());
                listener.onEvent(event);
            } catch (Throwable e) {
                getExceptionHandler().onException(listener, event, e);
            }/*from  www. j a v  a 2s  .  co m*/
            return null;
        }
    }));
}

From source file:edu.lternet.pasta.portal.HarvestReportServlet.java

private void executeHarvesterReportManager() {
    HarvestReportManager harvestReportManager = new HarvestReportManager(harvesterPath, harvesterReportTTL);
    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(harvestReportManager);
    executorService.shutdown();//from  w  ww. j  a  v a 2 s.c  o m
}

From source file:com.irusist.xiaoao.turntable.service.RequestService.java

/**
 * http??//from www  . jav a 2s. co  m
 *
 * @param token
 *         oauth?token
 */
public void execute(ExecutorService pool, final String account, final String token) {
    pool.execute(new Runnable() {
        @Override
        public void run() {
            request(account, token);
        }
    });
}

From source file:com.fly1tkg.streamfileupload.FileUploadFacade.java

public void post(final String url, final String fileKey, final File file, final String contentType,
        final Map<String, String> params, final FileUploadCallback callback) {

    if (null == callback) {
        throw new RuntimeException("FileUploadCallback should not be null.");
    }// w  w  w. j av a 2s. c  om

    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(new Runnable() {
        public void run() {
            try {
                HttpPost httpPost = new HttpPost(url);

                FileBody fileBody;
                if (null == contentType) {
                    fileBody = new FileBody(file);
                } else {
                    fileBody = new FileBody(file, contentType);
                }

                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                if (null == fileKey) {
                    entity.addPart(DEFAULT_FILE_KEY, fileBody);
                } else {
                    entity.addPart(fileKey, fileBody);
                }

                if (null != params) {
                    for (Map.Entry<String, String> e : params.entrySet()) {
                        entity.addPart(e.getKey(), new StringBody(e.getValue()));
                    }
                }

                httpPost.setEntity(entity);

                upload(httpPost, callback);
            } catch (UnsupportedEncodingException e) {
                callback.onFailure(-1, null, e);
            }
        }
    });
}

From source file:stroom.util.TestRoundRobinSet.java

@Test
public void testSync() throws InterruptedException {
    final RoundRobinSet<RoundRobinSetTestObject> rrList = new RoundRobinSet<RoundRobinSetTestObject>();
    rrList.add(new RoundRobinSetTestObject(1));
    rrList.add(new RoundRobinSetTestObject(2));
    rrList.add(new RoundRobinSetTestObject(N3));
    rrList.add(new RoundRobinSetTestObject(N4));

    final MutableLong failureCount = new MutableLong(0);

    final ExecutorService executorService = Executors.newCachedThreadPool();
    for (int i = 0; i < 10; i++) {
        executorService.execute(() -> {
            for (int j = 0; j < 100; j++) {
                ThreadUtil.sleepUpTo(10);

                try {
                    getString(rrList);//from www.j a va2  s. c o  m
                } catch (final Throwable e) {
                    System.err.println(e.getMessage());
                    failureCount.increment();
                }
            }
        });
    }

    executorService.shutdown();
    executorService.awaitTermination(2, TimeUnit.MINUTES);

    Assert.assertEquals(0, failureCount.longValue());
}

From source file:com.google.api.ads.adwords.awreporting.server.kratu.KratuProcessor.java

public void processKratus(Long topAccountId, Set<Long> accountIdsSet, 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, accountIdsSet, storageHelper, dateStart,
            dateEnd);//  w w w.  j  a va  2s.  c o  m

    ExecutorService executorService = Executors.newFixedThreadPool(1);
    runnableKratu.setLatch(latch);
    executorService.execute(runnableKratu);

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

From source file:org.emergya.backtrackTSP.BackTrackingTSP.java

private void run(final ExecutorService executor, final Runnable aStar) {
    executor.execute(aStar);
}

From source file:edu.cmu.lti.oaqa.bioasq.concept.retrieval.GoPubMedConceptRetrievalExecutor.java

@Override
public void process(JCas jcas) throws AnalysisEngineProcessException {
    AbstractQuery aquery = TypeUtil.getAbstractQueries(jcas).stream().findFirst().get();
    String queryString = bopQueryStringConstructor.construct(aquery).replaceAll("[^A-Za-z0-9_\\-\"]+", " ");
    LOG.info("Query string: {}", queryString);
    List<ConceptSearchResult> concepts = Collections.synchronizedList(new ArrayList<>());
    ExecutorService es = Executors.newCachedThreadPool();
    for (BioASQUtil.Ontology ontology : BioASQUtil.Ontology.values()) {
        es.execute(() -> {
            try {
                concepts.addAll(BioASQUtil.searchOntology(service, jcas, queryString, pages, hits, ontology));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }/*from w  w w.  j a v  a2 s.  c  o  m*/
        });
    }
    es.shutdown();
    try {
        if (!es.awaitTermination(timeout, TimeUnit.MINUTES)) {
            LOG.warn("Timeout occurs for one or some concept retrieval services.");
        }
    } catch (InterruptedException e) {
        throw new AnalysisEngineProcessException(e);
    }
    Map<String, List<ConceptSearchResult>> onto2concepts = concepts.stream()
            .collect(groupingBy(ConceptSearchResult::getSearchId));
    for (Map.Entry<String, List<ConceptSearchResult>> entry : onto2concepts.entrySet()) {
        List<ConceptSearchResult> results = entry.getValue();
        LOG.info("Retrieved {} concepts from {}", results.size(), entry.getKey());
        if (LOG.isDebugEnabled()) {
            results.stream().limit(3).forEach(c -> LOG.debug(" - {}", TypeUtil.toString(c)));
        }
    }
    TypeUtil.rankedSearchResultsByScore(concepts, limit).forEach(ConceptSearchResult::addToIndexes);
}

From source file:org.ros.android.acm_serial.PollingInputStream.java

/**
 * @param inputStream/*w ww  .j  a va2 s .  c o  m*/
 *          the {@link InputStream} to read from
 * @param executorService
 *          used to execute the read loop
 */
public PollingInputStream(final InputStream inputStream, ExecutorService executorService) {
    readBuffer = new byte[BUFFER_CAPACITY];
    readPosition = 0;
    writePosition = 0;
    executorService.execute(new CancellableLoop() {
        @Override
        protected void loop() throws InterruptedException {
            try {
                while (remaining() < READ_SIZE) {
                    if (readPosition < remaining()) {
                        // There isn't enough room to compact the buffer yet. We will most
                        // likely start dropping messages.
                        log.error("Not enough room to compact buffer.");
                        Thread.yield();
                        continue;
                    }
                    synchronized (readBuffer) {
                        int remaining = remaining();
                        System.arraycopy(readBuffer, writePosition, readBuffer, 0, remaining);
                        writePosition = remaining;
                        readPosition = 0;
                        if (DEBUG) {
                            log.info(String.format("Buffer compacted. %d bytes remaining.", remaining()));
                        }
                    }
                }
                int bytesRead = inputStream.read(readBuffer, writePosition, READ_SIZE);
                if (bytesRead < 0) {
                    throw new IOException("Stream closed.");
                }
                writePosition += bytesRead;
            } catch (IOException e) {
                throw new RosRuntimeException(e);
            }
        }
    });
}

From source file:org.pepstock.jem.gwt.server.services.StatisticsManager.java

/**
 * Calculates and returns last sample of JEM statistics
 * /*from  ww  w .  j av  a2  s  . co m*/
  * @return last sample of statistics
 * @throws ServiceMessageException if any exception occurs 
  */
public LightSample getCurrentSample() throws ServiceMessageException {
    // Remember that it uses QUEUES CURRENT permission to check if
    // it can get statistics 
    // checks if the user is authorized
    // if not, this method throws an exception
    try {
        checkAuthorization(new StringPermission(Permissions.ADMINISTRATION_CLUSTER_FOLDER));
    } catch (Exception e) {
        LogAppl.getInstance().ignore(e.getMessage(), e);
        try {
            checkAuthorization(new StringPermission(Permissions.ADMINISTRATION_NODES_FOLDER));
        } catch (Exception e1) {
            LogAppl.getInstance().ignore(e1.getMessage(), e1);
            checkAuthorization(new StringPermission(Permissions.ADMINISTRATION_QUEUES_FOLDER));
        }
    }

    LightSample lightSample = null;

    // extracts and collects all members 
    Cluster cluster = getInstance().getCluster();
    Set<Member> listOfNodes = new HashSet<Member>();
    for (Member member : cluster.getMembers()) {
        listOfNodes.add(member);
    }
    // if collections is not empty (must be!)
    if (!listOfNodes.isEmpty()) {

        //creates the sample 
        // setting all attributes necessary
        String key = DateFormatter.getCurrentDate(Sample.FORMAT);
        String[] times = StringUtils.split(key, ' ');

        lightSample = new LightSample();
        lightSample.setKey(key);
        lightSample.setDate(times[0]);
        lightSample.setTime(times[1]);

        // schedules a multi task on all memebers to get data
        MultiTask<LightMemberSample> task = new MultiTask<LightMemberSample>(new GetRealtimeSample(lightSample),
                listOfNodes);
        ExecutorService executorService = getInstance().getExecutorService();
        executorService.execute(task);
        try {
            // gets the results from all members
            Collection<LightMemberSample> results = task.get();
            lightSample.getMembers().addAll(results);
        } catch (Exception e) {
            LogAppl.getInstance().emit(UserInterfaceMessage.JEMG018E, e);
        }
    }
    return lightSample;
}