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:edu.wpi.checksims.util.threading.ParallelAlgorithm.java

/**
 * Internal backend: Execute given tasks on a new thread pool.
 *
 * Expects Callable tasks, with non-void returns. If the need for void returning functions emerges, might need
 * another version of this?//from  w  w w  . ja va  2s.  c  om
 *
 * @param tasks Tasks to execute
 * @param <T> Type returned by the tasks
 * @return Collection of Ts
 */
private static <T, T2 extends Callable<T>> Collection<T> executeTasks(Collection<T2> tasks) {
    checkNotNull(tasks);

    if (tasks.size() == 0) {
        logs.warn("Parallel execution called with no tasks - no work done!");
        return new ArrayList<>();
    }

    if (executor.isShutdown()) {
        throw new RuntimeException("Attempted to call executeTasks while executor was shut down!");
    }

    logs.info("Starting work using " + threadCount + " threads.");

    // Invoke the executor on all the worker instances
    try {
        // Create a monitoring thread to show progress
        MonitorThread monitor = new MonitorThread(executor);
        Thread monitorThread = new Thread(monitor);
        monitorThread.start();

        List<Future<T>> results = executor.invokeAll(tasks);

        // Stop the monitor
        monitor.shutDown();

        // Unpack the futures
        ArrayList<T> unpackInto = new ArrayList<>();

        for (Future<T> future : results) {
            try {
                unpackInto.add(future.get());
            } catch (ExecutionException e) {
                executor.shutdownNow();
                logs.error("Fatal error in executed job!");
                throw new RuntimeException("Error while executing worker for future", e.getCause());
            }
        }

        return unpackInto;
    } catch (InterruptedException e) {
        executor.shutdownNow();
        logs.error("Execution of Checksims was interrupted!");
        throw new RuntimeException(e);
    } catch (RejectedExecutionException e) {
        executor.shutdownNow();
        logs.error("Could not schedule execution of all comparisons --- possibly too few resources available?");
        throw new RuntimeException(e);
    }
}

From source file:com.controller.CPMEndOfDay.java

public static void getEODData() throws InterruptedException, IOException, JSONException {
    System.out.println("EOD DATA THREAD RUNNING.");
    try {//  www  . j a v  a  2s.  com
        String currUsername = CMAIN.reportUser().getUsername();
        HttpResponse<JsonNode> resp;

        ArrayList<SingleOrder> boughtOrders = new ArrayList<>();
        ArrayList<SingleOrder> soldOrders = new ArrayList<>();

        String currentTime = new SimpleDateFormat("HH:mm").format(new Date());
        String timeToCompare = "16:30";
        int x = currentTime.compareTo(timeToCompare);

        //INIT CLIENT
        CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
        client.start();

        //REQUEST
        HttpGet request;

        if (x >= 0) {
            request = new HttpGet("http://139.59.17.119:8080/api/pm/eod/" + currUsername + "/0");
        } else {
            request = new HttpGet("http://139.59.17.119:8080/api/pm/eod/" + currUsername + "/1");
        }

        //GET AND PARSE RESPONSE
        Future<org.apache.http.HttpResponse> future = client.execute(request, null);
        org.apache.http.HttpResponse response = future.get();
        String json_string = EntityUtils.toString(response.getEntity());
        JSONArray arrJson = new JSONArray(json_string);

        //GET ORDERS FROM ARRAY
        ArrayList<SingleOrder> arrayOrders = new ArrayList<>();

        for (int i = 0; i < arrJson.length(); i++) {
            JSONObject currentOrder = arrJson.getJSONObject(i);
            SingleOrder currentSingleOrder = JsonParsing.parseJsonToSingleOrderObject(currentOrder.toString());

            //DO THE DATE PART
            if (currentSingleOrder.getStatus().equals("Executed")) {
                // System.out.println("# executed by :" + currUsername);
                arrayOrders.add(currentSingleOrder);
            }
        }

        for (SingleOrder o : arrayOrders) {
            if (o.getAction().equals("Sell")) {
                soldOrders.add(o);
            } else if (o.getAction().equals("Buy")) {
                boughtOrders.add(o);
            }
        }

        setBought(boughtOrders);
        setSold(soldOrders);

        //DONT FORGET TO KILL CLIENT
        try {
            client.close();
        } catch (IOException ex) {
            Logger.getLogger(CPMOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (ExecutionException ex) {
        Logger.getLogger(CPMEndOfDay.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.intuit.karate.cucumber.CucumberRunner.java

public static KarateStats parallel(Class clazz, int threadCount, String reportDir) {
    KarateStats stats = KarateStats.startTimer();
    ExecutorService executor = Executors.newFixedThreadPool(threadCount);
    CucumberRunner runner = new CucumberRunner(clazz);
    List<FeatureFile> featureFiles = runner.getFeatureFiles();
    List<Callable<KarateJunitFormatter>> callables = new ArrayList<>(featureFiles.size());
    int count = featureFiles.size();
    for (int i = 0; i < count; i++) {
        int index = i + 1;
        FeatureFile featureFile = featureFiles.get(i);
        callables.add(() -> {//w w  w .  java 2s.c o  m
            String threadName = Thread.currentThread().getName();
            KarateJunitFormatter formatter = getFormatter(reportDir, featureFile);
            logger.info(">>>> feature {} of {} on thread {}: {}", index, count, threadName,
                    featureFile.feature.getPath());
            runner.run(featureFile, formatter);
            logger.info("<<<< feature {} of {} on thread {}: {}", index, count, threadName,
                    featureFile.feature.getPath());
            formatter.done();
            return formatter;
        });
    }
    try {
        List<Future<KarateJunitFormatter>> futures = executor.invokeAll(callables);
        stats.stopTimer();
        for (Future<KarateJunitFormatter> future : futures) {
            KarateJunitFormatter formatter = future.get();
            stats.addToTestCount(formatter.getTestCount());
            stats.addToFailCount(formatter.getFailCount());
            stats.addToSkipCount(formatter.getSkipCount());
            stats.addToTimeTaken(formatter.getTimeTaken());
            if (formatter.isFail()) {
                stats.addToFailedList(formatter.getFeaturePath());
            }
        }
        stats.printStats(threadCount);
        return stats;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.controller.CTraderOrderMANIAC.java

public static List<Block> updateBlockOrderHistory()
        throws InterruptedException, ExecutionException, IOException, JSONException {
    String currUsername = CMAIN.reportUser().getUsername();
    HttpResponse<JsonNode> resp;/* w  ww .  j a va  2  s.  c  om*/

    //INIT CLIENT
    CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();

    //REQUEST
    HttpGet request = new HttpGet("http://139.59.17.119:8080/api/trader/blocks/" + currUsername);

    //GET AND PARSE RESPONSE
    Future<org.apache.http.HttpResponse> future = client.execute(request, null);
    org.apache.http.HttpResponse response = future.get();
    String json_string = EntityUtils.toString(response.getEntity());
    JSONArray arrJson = new JSONArray(json_string);
    System.out.println("ASYNC JSONARRAY IS : " + arrJson.toString());

    //PARSE ARRAY INTO SINGLE ORDERS
    ArrayList<Block> arrayBlock = new ArrayList<>();
    for (int i = 0; i < arrJson.length(); i++) {
        JSONObject currentBlock = new JSONObject();
        try {
            currentBlock = arrJson.getJSONObject(i);
        } catch (JSONException ex) {
            Logger.getLogger(CTraderOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
        }
        Block currBlock = JsonParsing.parseJsonToBlockObject(currentBlock.toString());
        arrayBlock.add(currBlock);
    }
    blockHistory = arrayBlock;

    //DONT FORGET TO KILL CLIENT
    try {
        client.close();
    } catch (IOException ex) {
        Logger.getLogger(CPMOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
    }

    //RETURN ORDERS RETRIEVED
    if (!blockHistory.isEmpty()) {
        return blockHistory;
    } else {
        System.out.println("ASYNC BLOCK HISTORY IS EMPTY.");
        return null;
    }
}

From source file:com.controller.CTraderOrderMANIAC.java

public static List<SingleOrder> updateOrders()
        throws InterruptedException, IOException, JSONException, ExecutionException {

    String currUsername = CMAIN.reportUser().getUsername();
    HttpResponse<JsonNode> resp;/*w  w w  . j av  a2s.c  o  m*/
    System.out.println("Username in update orders is: " + currUsername);
    //INIT CLIENT
    CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
    client.start();

    //REQUEST
    HttpGet request = new HttpGet("http://139.59.17.119:8080/api/trader/orders/" + currUsername);

    //GET AND PARSE RESPONSE
    Future<org.apache.http.HttpResponse> future = client.execute(request, null);
    org.apache.http.HttpResponse response = future.get();
    String json_string = EntityUtils.toString(response.getEntity());
    System.out.println("ASYNC JSON STRING IS : " + json_string);
    JSONArray arrJson = new JSONArray(json_string);
    System.out.println("ASYNC JSONARRAY IS : " + arrJson.toString());

    //PARSE ARRAY INTO SINGLE ORDERS
    List<SingleOrder> arrayOrders = new ArrayList<>();
    for (int i = 0; i < arrJson.length(); i++) {
        JSONObject currentOrder = new JSONObject();
        try {
            currentOrder = arrJson.getJSONObject(i);
        } catch (JSONException ex) {
            Logger.getLogger(CTraderOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
        }
        SingleOrder currentSingleOrder = JsonParsing.parseJsonToSingleOrderObject(currentOrder.toString());

        arrayOrders.add(currentSingleOrder);
    }
    arrayOrdersMaster = arrayOrders;
    System.out.println("-----------------> THIS ARRAY IS: " + arrayOrdersMaster.size());
    //DONT FORGET TO KILL CLIENT
    try {
        client.close();
    } catch (IOException ex) {
        Logger.getLogger(CPMOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
    }

    //RETURN ORDERS RETRIEVED
    if (!arrayOrdersMaster.isEmpty()) {
        return arrayOrdersMaster;
    } else {
        System.out.println("ASYNC ORDERS IS EMPTY.");
        return null;
    }
}

From source file:com.dattack.dbtools.drules.engine.DrulesEngine.java

private static SourceResultGroup getSourceResultsList(final List<SourceBean> sourceList)
        throws DrulesNestableException {

    final ExecutorService executorService = Executors.newCachedThreadPool(createThreadFactory());

    final List<Future<SourceResult>> futureList = new ArrayList<>();

    for (final SourceBean sourceBean : sourceList) {
        futureList.add(executorService.submit(new SourceExecutor(sourceBean,
                ConfigurationUtils.cloneConfiguration(ThreadContext.getInstance().getConfiguration()))));
    }//from   w  w  w . j  a v  a2 s  . com

    final SourceResultGroup sourceResultList = new SourceResultGroup();

    for (final Future<SourceResult> future : futureList) {
        try {
            sourceResultList.add(future.get());
        } catch (InterruptedException | ExecutionException e) {
            throw new DrulesNestableException(e);
        }
    }
    executorService.shutdown();

    return sourceResultList;
}

From source file:controllers.GWT2Controller.java

private static Object chainDo(GWT2ChainRuntime chain) {
    Future<?> f = chain.getFuture();
    while (f.isDone() || f.isCancelled()) {
        await(100);//from ww w .  ja v  a 2  s  .  c  o  m
    }
    try {
        return f.get();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.google.code.stackexchange.client.examples.AsyncApiExample.java

/**
 * Process command line./*from   w ww .j a v a  2  s.  c  om*/
 * 
 * @param line the line
 * @param options the options
 * 
 * @throws Exception the exception
 */
private static void processCommandLine(CommandLine line, Options options) throws Exception {
    if (line.hasOption(HELP_OPTION)) {
        printHelp(options);
    } else if (line.hasOption(APPLICATION_KEY_OPTION)) {
        final String keyValue = line.getOptionValue(APPLICATION_KEY_OPTION);

        final StackExchangeApiClientFactory factory = StackExchangeApiClientFactory.newInstance(keyValue);
        final AsyncStackExchangeApiClient client = factory.createAsyncStackExchangeApiClient();
        System.out.println("Fetching badges and tags asynchronously.");
        Future<List<Badge>> badgesFuture = client.getBadges();
        Future<List<Tag>> tagsFuture = client.getTags();
        System.out.println("Done fetching badges and tags asynchronously. Now blocking for result.");
        List<Badge> badges = badgesFuture.get();
        System.out.println("============ Badges ============");
        for (Badge badge : badges) {
            printResult(badge);
        }
        List<Tag> tags = tagsFuture.get();
        System.out.println("============ Tags ============");
        for (Tag tag : tags) {
            printResult(tag);
        }

    } else {
        printHelp(options);
    }
}

From source file:com.newmainsoftech.spray.slingong.datastore.testmodel.book.Author.java

/**
 * Returned Author model object has preset key. 
 *///from w  ww  . jav  a  2  s .  c  om
@Transactional(propagation = Propagation.REQUIRED)
public static Author createNewAuthor(String name) {
    Future<KeyRange> futureKeys = Datastore.allocateIdsAsync(Author.class, 1);
    Author author = new Author();
    author.setName(name);
    try {
        author.setKey(futureKeys.get().getStart());
    } catch (Throwable throwable) {
        if (logger.isErrorEnabled()) {
            logger.error(String.format("Failed to generate key asynchronously for new Author entity.%n"
                    + "Going to attempt to regenrate it synchronously."), throwable);
        }
        author.setKey(Datastore.allocateId(Author.class));
    }
    GlobalTransaction gtx = Datastore.getCurrentGlobalTransaction();
    gtx.put(author);

    return author;
}

From source file:com.gigaspaces.persistency.MongoClientConnector.java

private static long waitFor(List<Future<? extends Number>> replies) {

    long total = 0;

    for (Future<? extends Number> future : replies) {
        try {/*from  w  w w  .ja  v  a2 s.c  o  m*/
            total += future.get().longValue();
        } catch (InterruptedException e) {
            throw new SpaceMongoException("Number of async operations: " + replies.size(), e);
        } catch (ExecutionException e) {
            throw new SpaceMongoException("Number of async operations: " + replies.size(), e);
        }
    }

    return total;
}