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() throws InterruptedException, ExecutionException;

Source Link

Document

Waits if necessary for the computation to complete, and then retrieves its result.

Usage

From source file:ijfx.explorer.datamodel.wrappers.ImageRecordIconizer.java

@Override
public void open() throws Exception {

    HashMap<String, Object> inputs = new HashMap<>();
    inputs.put("file", imageRecord.getFile());
    inputs.put("imageId", imageId);
    Future<CommandModule> run = commandService.run(OpenImageFX.class, true, inputs);
    run.get();
    activityService.open(DisplayContainer.class);
}

From source file:com.nts.alphamale.handler.ExecutorHandler.java

/**
 * parallel execute synchronous commandline
 * @param cmdList/*from   w  w w. ja  v  a2s.c  om*/
 * @param timeoutSecond
 * @return
 */
public List<Map<String, Object>> executeParallel(List<CommandLine> cmdList, int timeoutSecond) {
    ExecutorService executor = Executors.newCachedThreadPool();
    List<Future<Map<String, Object>>> resultList;
    List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
    List<SynchronousTask> taskList = new ArrayList<SynchronousTask>();
    for (CommandLine cmd : cmdList) {
        taskList.add(new SynchronousTask(cmd, timeoutSecond * 1000));
    }
    try {
        resultList = executor.invokeAll(taskList, timeoutSecond + 10, TimeUnit.SECONDS);
        for (Future<Map<String, Object>> result : resultList) {
            results.add(result.get());
        }
    } catch (InterruptedException e) {
        log.error(e.getMessage());
    } catch (ExecutionException e) {
        log.error(e.getMessage());
    }
    if (!executor.isShutdown()) {
        executor.shutdown();
    }
    return results;
}

From source file:com.qpark.eip.core.spring.lockedoperation.EipTest.java

/**
 * Test to run several synchronous {@link LockableOperation}s in parallel.
 *//* w  w w .  j  a v a  2 s . c o  m*/
@Test
public void testLockableOperationTestSyncCall() {
    this.logger.debug("+testLockableOperationTestSyncCall");
    int threadCount = 4;

    OperationEventEnumType start = OperationEventEnumType.START;
    LockableOperationContext context = new LockableOperationContext();
    List<OperationStateEnumType> status = new ArrayList<>();
    Callable<Void> task = () -> {
        OperationStateEnumType value = EipTest.this.operationSync
                .runOperation(EipTest.this.operationSync.getUUID(), start, context);
        status.add(value);
        this.logger.debug(" testLockableOperationTestSyncCall returned {}", value);
        return null;
    };
    List<Callable<Void>> tasks = Collections.nCopies(threadCount, task);
    ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
    List<Future<Void>> futures;
    try {
        futures = executorService.invokeAll(tasks);
        List<Void> resultList = new ArrayList<>(futures.size());
        // Check for exceptions
        for (Future<Void> future : futures) {
            // Throws an exception if an exception was thrown by the task.
            resultList.add(future.get());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    int runnings = status.stream().filter(s -> s.equals(OperationStateEnumType.RUNNING))
            .collect(Collectors.toList()).size();
    int idle = status.stream().filter(s -> s.equals(OperationStateEnumType.IDLE)).collect(Collectors.toList())
            .size();
    Assert.assertEquals("No the right number of sync proccesses got the RUNNING return.", runnings,
            threadCount - 1);
    Assert.assertEquals("To many IDLE sync processes", idle, 1);
    OperationStateEnumType idleResult = this.operationSync.runOperation(this.operationSync.getUUID(),
            OperationEventEnumType.CHECK_STATE, context);
    Assert.assertEquals("Cleanup missing at sync processes", idleResult, OperationStateEnumType.IDLE);
    this.logger.debug("+testLockableOperationTestSyncCall");
}

From source file:io.github.mmichaelis.selenium.client.provider.AbstractWebDriverProviderTest.java

private WebDriver getDriverFromThread(final WebDriverProvider driverProvider)
        throws InterruptedException, ExecutionException {
    final Callable<WebDriver> driverCallable = new WebDriverCallable(driverProvider);
    final ExecutorService executor = newCachedThreadPool();
    final Future<WebDriver> result = executor.submit(driverCallable);
    return result.get();
}

From source file:com.clustercontrol.nodemap.util.SearchConnectionExecutor.java

public List<Association> execute() throws Exception {
    List<Association> result = new ArrayList<Association>();
    List<Future<List<Association>>> futures = new ArrayList<Future<List<Association>>>();
    // ????MAC???
    // ??????ID????????ID????
    macFacilityMap = new ConcurrentHashMap<String, List<String>>();
    for (String id : facilityIdList) {
        if (!bean.isNode(id)) {
            continue;
        }//from   w  w w. ja v a2s  .  c  o m

        NodeInfo node = bean.getNode(id);
        for (NodeNetworkInterfaceInfo info : node.getNodeNetworkInterfaceInfo()) {
            // NIC?MAC??????
            String nicMacAddress = info.getNicMacAddress().toUpperCase();
            if (!macFacilityMap.containsKey(nicMacAddress)) {
                // ????????MAC??
                macFacilityMap.put(nicMacAddress, new ArrayList<String>());
            }
            macFacilityMap.get(nicMacAddress).add(id);
        }
    }
    now = HinemosTime.currentTimeMillis();
    m_log.debug("get mac map : " + (now - start) + "ms");

    for (String facilityId : facilityIdList) {
        if (!bean.isNode(facilityId)) {
            // ??????
            continue;
        }

        NodeInfo node = bean.getNode(facilityId);

        if (!node.getPlatformFamily().equals("NW_EQUIPMENT")) {
            // ????????
            continue;
        }

        if (isL3 && !node.getHardwareType().equals("L3")) {
            // L3????????L3????????
            continue;
        }

        futures.add(_executor.submit(new SearchConnection(node)));
    }

    // ?????????????
    _executor.shutdown();

    // ??????
    for (Future<List<Association>> future : futures) {
        result.addAll(future.get());
    }
    now = HinemosTime.currentTimeMillis();
    m_log.debug("end : " + (now - start) + "ms");
    return result;
}

From source file:org.nmdp.service.epitope.dropwizard.EpitopeServiceApplication.java

/**
 * Dropwizard service runner.  Application resources are registered here.
 *//*from w w w.  ja va  2s  . c  om*/
@Override
public void runService(final EpitopeServiceConfiguration configuration, final Environment environment)
        throws Exception {

    Injector injector = Guice.createInjector(
            new ConfigurationModule(ConfigurationBindings.class, configuration), new LocalServiceModule(),
            new ResourceModule(), new AbstractModule() {
                @Override
                protected void configure() {
                    DBI dbi = new DBIFactory().build(environment, configuration.getDataSourceFactory(),
                            "sqlite");
                    bind(DBI.class).toInstance(dbi);
                }
            });

    environment.getObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
            .setSerializationInclusion(Include.NON_NULL)
            .enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

    // todo: generalize dependency graph (latches?)
    //Runnable initializers = serial(
    //       parallel(
    //          () -> injector.getInstance(GGroupInitializer.class).loadGGroups(),
    //          () -> injector.getInstance(AlleleCodeInitializer.class).loadAlleleCodes(),
    //          serial(
    //             () -> injector.getInstance(AlleleInitializer.class).loadAlleles()),
    //             () -> injector.getInstance(ImgtImmuneGroupInitializer.class).loadAlleleScores()),
    //       parallel(
    //          () -> injector.getInstance(EpitopeService.class).buildMaps(),
    //          () -> injector.getInstance(FrequencyService.class).buildFrequencyMap(),
    //          () -> injector.getInstance(DbiAlleleCodeResolver.class).buildAlleleCodeMap()));

    Runnable initializers = serial(() -> injector.getInstance(GGroupInitializer.class).loadGGroups(),
            () -> injector.getInstance(AlleleCodeInitializer.class).loadAlleleCodes(),
            () -> injector.getInstance(AlleleInitializer.class).loadAlleles(),
            () -> injector.getInstance(ImmuneGroupInitializer.class).loadImmuneGroups(),
            () -> injector.getInstance(EpitopeService.class).buildAlleleGroupMaps(),
            () -> injector.getInstance(FrequencyService.class).buildFrequencyMap());
    //                 () -> injector.getInstance(DbiAlleleCodeResolver.class).buildAlleleCodeMap());

    long refreshMillis = injector.getInstance(Key.get(Long.class, RefreshMillis.class));

    environment.lifecycle().manage(new Managed() {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, r -> {
            Thread t = new Thread(r, "InitializerThread");
            t.setDaemon(true);
            return t;
        });

        @Override
        public void stop() throws Exception {
            scheduler.shutdownNow();
        }

        @Override
        public void start() throws Exception {
            Future<?> init = scheduler.submit(initializers);
            init.get();
            scheduler.scheduleAtFixedRate(initializers, refreshMillis, refreshMillis, MILLISECONDS);
        }
    });

    final AlleleResource alleleResource = injector.getInstance(AlleleResource.class);
    environment.jersey().register(alleleResource);

    final GroupResource groupResource = injector.getInstance(GroupResource.class);
    environment.jersey().register(groupResource);

    final MatchResource matchResource = injector.getInstance(MatchResource.class);
    environment.jersey().register(matchResource);

    environment.jersey().register(new org.nmdp.service.epitope.resource.impl.ExceptionMapper());

    // eriktodo: multibinder for health checks
    final GlClientHealthCheck glClientHealthCheck = injector.getInstance(GlClientHealthCheck.class);
    environment.healthChecks().register("glClient", glClientHealthCheck);
}

From source file:com.msopentech.odatajclient.engine.it.AsyncTestITCase.java

@Test
public void updateEntity() throws InterruptedException, ExecutionException {
    final URI uri = client.getURIBuilder(testDefaultServiceRootURL).appendEntityTypeSegment("Product")
            .appendKeySegment(-10).build();

    final ODataRetrieveResponse<ODataEntity> entityRes = client.getRetrieveRequestFactory()
            .getEntityRequest(uri).execute();
    final ODataEntity entity = entityRes.getBody();
    entity.getAssociationLinks().clear();
    entity.getNavigationLinks().clear();
    entity.getEditMediaLinks().clear();//  www. ja  va 2 s  .  c o m
    entity.getProperty("Description")
            .setValue(client.getPrimitiveValueBuilder().setText("AsyncTest#updateEntity").build());

    final ODataEntityUpdateRequest updateReq = client.getCUDRequestFactory().getEntityUpdateRequest(uri,
            UpdateType.MERGE, entity);
    updateReq.setIfMatch(entityRes.getEtag());
    final Future<ODataEntityUpdateResponse> futureRes = updateReq.asyncExecute();

    while (!futureRes.isDone()) {
    }

    final ODataEntityUpdateResponse res = futureRes.get();
    assertNotNull(res);
    assertEquals(204, res.getStatusCode());
}

From source file:it.geosolutions.tools.io.CopyTreeTest.java

@Test
public void copyTreeTest() throws Exception {
    LOGGER.info("START: CopyTreeTest");
    File srcMount = TestData.file(this, ".");
    CopyTree act = new CopyTree(
            FileFilterUtils.or(FileFilterUtils.directoryFileFilter(), FileFilterUtils.fileFileFilter()), cs,
            srcMount, destMount);/*w ww.  j a va 2s .c  o m*/
    act.addCollectingListener(new DefaultProgress("COLLECTING"));
    act.addCopyListener(new DefaultProgress("COPY"));
    int workSize = act.copy();
    try {
        while (workSize-- > 0) {
            Future<File> future = cs.take();
            try {
                LOGGER.info("copied file: " + future.get());
            } catch (ExecutionException e) {
                LOGGER.info(e.getLocalizedMessage(), e);
                Assert.fail();
            }
        }
    } catch (InterruptedException e) {
        LOGGER.info(e.getLocalizedMessage(), e);
        Assert.fail();
    }
    LOGGER.info("STOP: CopyTreeTest");
}

From source file:com.easarrive.image.thumbor.executer.service.impl.SQSNotificationHandlerForThumbor.java

private List<NotificationHandleResult<Message, Boolean>> ergodicS3EventMessageRecord(final Message message,
        S3EventMessageContent messageContent) throws AWSPluginException {
    List<S3EventMessageRecord> recordList = messageContent.getRecords();
    if (recordList == null) {
        throw new AWSPluginException("The S3EventMessageRecord list is null");
    }/*from w ww. j a  v  a 2 s .  com*/
    if (recordList.size() < 1) {
        throw new AWSPluginException("The S3EventMessageRecord list is empty");
    }

    ExecutorService executorService = Executors.newCachedThreadPool();
    List<Future<NotificationHandleResult<Message, Boolean>>> resultList = new ArrayList<Future<NotificationHandleResult<Message, Boolean>>>();
    for (final S3EventMessageRecord s3EventMessageRecord : recordList) {
        Future<NotificationHandleResult<Message, Boolean>> future = executorService.submit(
                new SQSNotificationHandlerForThumborCallable(message, s3EventMessageRecord, generatePicture));
        resultList.add(future);
    }

    List<NotificationHandleResult<Message, Boolean>> resutList = new ArrayList<NotificationHandleResult<Message, Boolean>>();
    //??
    for (Future<NotificationHandleResult<Message, Boolean>> fs : resultList) {
        try {
            NotificationHandleResult<Message, Boolean> result = fs.get();
            if (logger.isInfoEnabled()) {
                logger.info("The SQS message record ({}) result to handle is {}", result.getMessageId(),
                        result.getData());
            }
            resutList.add(result);
            if (!result.getData()) {
                break;
            }
        } catch (Exception e) {
            if (logger.isErrorEnabled()) {
                logger.error(e.getMessage(), e);
            }
        } finally {
            //????????
            executorService.shutdown();
        }
    }
    return resutList;
}

From source file:main.ScorePipeline.java

/**
 * This method calculates similarities bin-based between yeast_human spectra
 * on the first data set against all yeast spectra on the second data set
 *
 * @param min_mz/*from w  ww .j  av a  2s . c  o m*/
 * @param max_mz
 * @param topN
 * @param percentage
 * @param yeast_and_human_file
 * @param is_precursor_peak_removal
 * @param fragment_tolerance
 * @param noiseFiltering
 * @param transformation
 * @param intensities_sum_or_mean_or_median
 * @param yeast_spectra
 * @param bw
 * @param charge
 * @param charge_situation
 * @throws IllegalArgumentException
 * @throws ClassNotFoundException
 * @throws IOException
 * @throws MzMLUnmarshallerException
 * @throws NumberFormatException
 * @throws ExecutionException
 * @throws InterruptedException
 */
private static void calculate_BinBasedScores(ArrayList<BinMSnSpectrum> yeast_spectra,
        ArrayList<BinMSnSpectrum> yeast_human_spectra, BufferedWriter bw, int charge, double precursorTol,
        double fragTol, String scoreType) throws IllegalArgumentException, ClassNotFoundException, IOException,
        MzMLUnmarshallerException, NumberFormatException, InterruptedException {
    ExecutorService excService = Executors
            .newFixedThreadPool(ConfigHolder.getInstance().getInt("thread.numbers"));
    List<Future<SimilarityResult>> futureList = new ArrayList<>();
    for (BinMSnSpectrum binYeastHumanSp : yeast_human_spectra) {
        int tmpMSCharge = binYeastHumanSp.getSpectrum().getPrecursor().getPossibleCharges().get(0).value;
        if (charge == 0 || tmpMSCharge == charge) {
            if (!binYeastHumanSp.getSpectrum().getPeakList().isEmpty() && !yeast_spectra.isEmpty()) {
                Calculate_Similarity similarity = new Calculate_Similarity(binYeastHumanSp, yeast_spectra,
                        fragTol, precursorTol);
                Future future = excService.submit(similarity);
                futureList.add(future);
            }
        }
    }
    SimilarityMethods method = SimilarityMethods.NORMALIZED_DOT_PRODUCT_STANDARD;
    if (scoreType.equals("spearman")) {
        method = SimilarityMethods.SPEARMANS_CORRELATION;
    } else if (scoreType.equals("pearson")) {
        method = SimilarityMethods.PEARSONS_CORRELATION;
    }
    for (Future<SimilarityResult> future : futureList) {
        try {
            SimilarityResult get = future.get();
            String tmp_charge = get.getSpectrumChargeAsString(), spectrum = get.getSpectrumName();
            double tmpPrecMZ = get.getSpectrumPrecursorMZ(), score = get.getScores().get(method);
            if (score == Double.MIN_VALUE) {
                LOGGER.info("The similarity for the spectrum " + spectrum
                        + " is too small to keep the record, therefore score is not computed.");
                // Means that score has not been calculated!
                //                    bw.write(tmp_Name + "\t" + tmp_charge + "\t" + tmpPrecMZ + "\t");
                //                    bw.write("NA" + "\t" + "NA" + "\t" + "NA" + "\t" + "NA");
            } else {
                bw.write(spectrum + "\t" + tmp_charge + "\t" + tmpPrecMZ + "\t" + get.getSpectrumToCompare()
                        + "\t" + score + "\n");
            }
        } catch (InterruptedException | ExecutionException e) {
            LOGGER.error(e);
        }
    }
}