Example usage for java.util.concurrent Future get

List of usage examples for java.util.concurrent Future get

Introduction

In this page you can find the example usage for java.util.concurrent Future get.

Prototype

V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException;

Source Link

Document

Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

Usage

From source file:org.hupo.psi.mi.psicquic.registry.PsicquicRegistryStatusChecker.java

private void checkAndResumeRegistryTasks() {

    for (Future f : runningTasks) {
        try {//from ww w . java  2  s . c  om
            f.get(threadTimeOut, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("The registry task was interrupted, we cancel the task.", e);
            if (!f.isCancelled()) {
                f.cancel(true);
            }
        } catch (ExecutionException e) {
            log.error("The registry task could not be executed, we cancel the task.", e);
            if (!f.isCancelled()) {
                f.cancel(true);
            }
        } catch (TimeoutException e) {
            log.error("Service task stopped because of time out " + threadTimeOut + " seconds.");

            if (!f.isCancelled()) {
                f.cancel(true);
            }
        } catch (Throwable e) {
            log.error("Service task stopped.", e);
            if (!f.isCancelled()) {
                f.cancel(true);
            }
        }
    }

    runningTasks.clear();
}

From source file:com.njmd.framework.utils.memcached.SpyMemcachedClient.java

/**
 * Set,1, ?false??.//from   w  w  w.  j a  va2  s  .c o m
 */
public boolean safeDelete(String key) {
    Future<Boolean> future = memcachedClient.delete(key);
    try {
        return future.get(1, TimeUnit.SECONDS);
    } catch (Exception e) {
        future.cancel(false);
    }
    return false;
}

From source file:de.innovationgate.wgpublisher.cluster.ClusterMember.java

private void refreshMemberInformation() {
    if (System.currentTimeMillis() - _memberInformationLastFetched > MEMBERINFORMATION_LATENCY_SECONDS * 1000
            || _memberInformation == null) {
        try {/* ww  w  . j a v  a  2s . com*/
            CollectMemberInformationTask task = new CollectMemberInformationTask();
            Future<MemberInformation> result = _clusterService.submitTo(this, task);
            if (result != null) {
                _memberInformation = result.get(MEMBERINFORMATION_FETCHTIMEOUT_SECONDS, TimeUnit.SECONDS);
                _memberInformationLastFetched = System.currentTimeMillis();
            }
        } catch (Throwable e) {
            WGFactory.getLogger().error("Failed to fetch clusterMemberInformation for '" + this + "'.", e);
        }
    }
}

From source file:apiserver.services.images.controllers.info.MetadataController.java

/**
 * get embedded metadata/*ww  w  .ja v  a2  s.  c  om*/
 *
 * @param documentId
 * @return height, width
 */
@ApiOperation(value = "Get the embedded metadata", response = Map.class)
@RequestMapping(value = "/info/{documentId}/metadata", method = { RequestMethod.GET })
public WebAsyncTask<Map> imageMetadataByImage(
        @ApiParam(name = "documentId", required = true, defaultValue = "8D981024-A297-4169-8603-E503CC38EEDA") @PathVariable(value = "documentId") String documentId) {
    final String _documentId = documentId;

    Callable<Map> callable = new Callable<Map>() {
        @Override
        public Map call() throws Exception {
            FileMetadataJob args = new FileMetadataJob();
            args.setDocumentId(_documentId);

            Future<Map> imageFuture = imageMetadataGateway.getMetadata(args);
            FileMetadataJob payload = (FileMetadataJob) imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

            return payload.getMetadata();
        }
    };

    return new WebAsyncTask<Map>(defaultTimeout, callable);
}

From source file:apiserver.services.pdf.service.ProcessPdfDDXCFService.java

public Object execute(Message<?> message) throws ColdFusionException {
    DDXPdfResult props = (DDXPdfResult) message.getPayload();

    try {/*from w w  w.  j ava  2s. co  m*/
        long startTime = System.nanoTime();
        Grid grid = verifyGridConnection();

        // Get grid-enabled executor service for nodes where attribute 'worker' is defined.
        ExecutorService exec = getColdFusionExecutor();

        Future<ByteArrayResult> future = exec
                .submit(new ProcessDDXCallable(props.getFile().getFileBytes(), props.getDdx()));

        ByteArrayResult _result = future.get(defaultTimeout, TimeUnit.SECONDS);
        props.setResult(_result.getBytes());

        long endTime = System.nanoTime();
        log.debug("execution times: CF=" + _result.getStats().getExecutionTime() + "ms -- total="
                + (endTime - startTime) + "ms");

        return props;
    } catch (Exception ge) {
        throw new RuntimeException(ge);
    }
}

From source file:apiserver.services.pdf.service.ExtractPdfTextCFService.java

public Object execute(Message<?> message) throws ColdFusionException {
    ExtractTextResult props = (ExtractTextResult) message.getPayload();

    try {/*from   w ww.  j ava 2 s  . c o  m*/
        long startTime = System.nanoTime();
        Grid grid = verifyGridConnection();

        // Get grid-enabled executor service for nodes where attribute 'worker' is defined.
        ExecutorService exec = getColdFusionExecutor();

        Future<StringResult> future = exec
                .submit(new ExtractTextCallable(props.getFile().getFileBytes(), props.getOptions()));

        StringResult _result = future.get(defaultTimeout, TimeUnit.SECONDS);
        props.setResult(_result.getResult());

        long endTime = System.nanoTime();
        log.debug("execution times: CF=" + _result.getStats().getExecutionTime() + "ms -- total="
                + (endTime - startTime) + "ms");

        return props;
    } catch (Exception ge) {
        throw new RuntimeException(ge);
    }
}

From source file:org.ppollack.symphony.faqbot.SymphonyFaqbot.java

public void handleIncomingMessage(ISymphonyMessage symphonyMessage) {

    String messageContent = symphonyMessage.getMessageText();
    ISymphonyUser author = symphonyMessage.getSymphonyUser();

    if (messageContent.toLowerCase().contains("hello")) {
        String messageToSend = "Hello " + author.getDisplayName() + "!";
        symphonyClient.sendMessage(symphonyMessage.getStreamId(), messageToSend);
        return;/*from  w ww. ja v  a 2  s  . c  om*/
    }

    LOG.info("processing message [" + messageContent + "] from user [" + author + "]...");
    Future<FaqbotResponse> responseFuture = requestExecutor.execute(author, messageContent);

    try {
        FaqbotResponse response = responseFuture.get(configurationProvider.getRequestProcessingTimeout(),
                TimeUnit.MILLISECONDS);
        sendResponse(symphonyMessage, response);
        LOG.info("sending response to [" + messageContent + "] from user [" + author + "], response is ["
                + response.getResponseText() + "]");

    } catch (Exception e) {
        LOG.error("failed to process message [" + messageContent + "] from user [" + author + "]", e);
        // TODO consider sending a message back to the author
    }
}

From source file:com.clustercontrol.repository.session.RepositoryRunManagementBean.java

/**
 * Quartz???<BR>/* www .j  a  v a2  s .c  o m*/
 * <P>
 * Quartz??????<BR>
 * <BR>
 * ?????????<BR>
 * @throws HinemosUnknown
 * @throws JobInfoNotFound
 *
 * @see com.clustercontrol.jobmanagement.factory.OperationJob#runJob()
 */
public void run() {
    if (duplicateExec.tryAcquire()) {
        try {
            if (countCheck()) {
                long start = HinemosTime.currentTimeMillis();
                RepositoryControllerBean controller = new RepositoryControllerBean();
                //?
                try {
                    List<String> facilityIdList = controller.getNodeFacilityIdList();
                    List<Future<Boolean>> futureList = new ArrayList<Future<Boolean>>();
                    //????
                    for (String facilityId : facilityIdList) {
                        futureList.add(_executorService.submit(new DeviceSearchTask(facilityId)));
                    }

                    //?
                    for (Future<Boolean> future : futureList) {
                        try {
                            future.get(60 * 1000, TimeUnit.MILLISECONDS);
                        } catch (TimeoutException e) {
                            // SNMP?????????????????
                            m_log.warn("run() : " + e.getClass().getName(), e);
                        } catch (InterruptedException e) {
                            m_log.warn("run() : " + e.getClass().getName(), e);
                        } catch (ExecutionException e) {
                            m_log.warn("run() : " + e.getClass().getName(), e);
                        }
                    }

                } catch (HinemosUnknown e) {
                    m_log.warn("run() : " + e.getClass().getSimpleName() + ", " + e.getMessage(), e);
                }
                m_log.info("auto device search : time=" + (HinemosTime.currentTimeMillis() - start) + "ms");
            }
        } finally {
            duplicateExec.release();
        }
    } else {
        m_log.warn("runningCheck is busy !!");
    }
}

From source file:apiserver.services.pdf.service.AddFooterToPdfCFService.java

public Object execute(Message<?> message) throws ColdFusionException {
    AddFooterPdfResult props = (AddFooterPdfResult) message.getPayload();

    try {//  w w w  .j  a v a2s. co  m
        long startTime = System.nanoTime();
        Grid grid = verifyGridConnection();

        // Get grid-enabled executor service for nodes where attribute 'worker' is defined.
        ExecutorService exec = getColdFusionExecutor();

        Future<ByteArrayResult> future = exec
                .submit(new AddFooterCallable(props.getFile().getFileBytes(), props.getOptions()));

        ByteArrayResult _result = future.get(defaultTimeout, TimeUnit.SECONDS);
        props.setResult(_result.getBytes());

        long endTime = System.nanoTime();
        log.debug("execution times: CF=" + _result.getStats().getExecutionTime() + "ms -- total="
                + (endTime - startTime) + "ms");

        return props;
    } catch (Exception ge) {
        throw new RuntimeException(ge);
    }
}

From source file:apiserver.services.pdf.service.AddHeaderToPdfCFService.java

public Object execute(Message<?> message) throws ColdFusionException {
    AddHeaderPdfResult props = (AddHeaderPdfResult) message.getPayload();

    try {//from ww  w. j av  a2s.c om
        long startTime = System.nanoTime();
        Grid grid = verifyGridConnection();

        // Get grid-enabled executor service for nodes where attribute 'worker' is defined.
        ExecutorService exec = getColdFusionExecutor();

        Future<ByteArrayResult> future = exec
                .submit(new AddFooterCallable(props.getFile().getFileBytes(), props.getOptions()));

        ByteArrayResult _result = future.get(defaultTimeout, TimeUnit.SECONDS);
        props.setResult(_result.getBytes());

        long endTime = System.nanoTime();
        log.debug("execution times: CF=" + _result.getStats().getExecutionTime() + "ms -- total="
                + (endTime - startTime) + "ms");

        return props;
    } catch (Exception ge) {
        throw new RuntimeException(ge);
    }
}