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:com.microsoft.azure.storage.util.KVCredentials.java

/**
 * Creates the access token//from   w ww  .j  a v a 2  s  .  com
 * 
 * @param authorization
 *            The authorization from the service
 * @param resource
 *            The resource being accessed
 * @param clientId
 *            The ClientID for this application
 * @param clientKey
 *            The Client Secret for this application
 * @return The access token to use to authenticate to the service
 */
private static AuthenticationResult getAccessTokenFromClientCredentials(String authorization, String resource,
        String clientId, String clientKey) {
    AuthenticationContext context = null;
    AuthenticationResult result = null;
    ExecutorService service = null;
    try {
        service = Executors.newFixedThreadPool(1);
        context = new AuthenticationContext(authorization, false, service);
        ClientCredential credentials = new ClientCredential(clientId, clientKey);
        Future<AuthenticationResult> future = context.acquireToken(resource, credentials, null);
        result = future.get();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        service.shutdown();
    }

    if (result == null) {
        throw new RuntimeException("authentication result was null");
    }
    return result;
}

From source file:no.ntnu.idi.socialhitchhiking.client.RequestTask.java

/**
 * Static method which adds elements and data to an xml file and sends it as a string to the server.
 * // w w w . ja va2 s. c o  m
 * @param req - {@link Request}
 * @return returns a subclass of {@link Response} to the input {@link Request}
 * @throws ClientProtocolException 
 * @throws MalformedURLException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws ExecutionException 
 * @throws InterruptedException 
 */
public static Response sendRequest(final Request req, final Context c)
        throws ClientProtocolException, IOException, InterruptedException, ExecutionException {
    /**
     * Code for putting all all network communication on separate thread as required by higher Android APIs
     */
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<Response> callable = new Callable<Response>() {
        @Override
        /**
         * This contains the actual code for initiating the communication
         */
        public Response call() throws ClientProtocolException, IOException {
            String xml = RequestSerializer.serialize(req);
            con = c;
            String url = con.getResources().getString(R.string.server_url);
            RequestTask requestTask = new RequestTask(url, xml);

            return ResponseParser.parse(requestTask.getResponse());
        }
    };
    /**
     * Execute and retrieve result from network operation
     */
    Future<Response> future = executor.submit(callable);
    Response ret = future.get();
    executor.shutdown();
    return ret;
}

From source file:com.dattack.dbcopy.engine.DbCopyJob.java

private static void showFutures(final List<Future<?>> futureList) {

    for (final Future<?> future : futureList) {
        try {/*w w w  .j av a 2  s  . co  m*/
            LOGGER.info("Future result: {}", future.get());
        } catch (final InterruptedException | ExecutionException e) {
            LOGGER.warn("Error getting computed result from Future object", e);
        }
    }
}

From source file:joachimeichborn.geotag.handlers.OpenTracksHandler.java

public static void openTracks(final String aPath, final String[] aFiles, final TracksRepo aTracksRepo) {
    final Job job = new Job("Reading tracks") {
        @Override// w w  w  . j  av a2  s .  c  om
        protected IStatus run(final IProgressMonitor aMonitor) {
            aMonitor.beginTask("Reading " + aFiles.length + " tracks", aFiles.length);

            int threads = 2 * Runtime.getRuntime().availableProcessors();
            logger.fine("Using " + threads + " cores for loading tracks");

            final ExecutorService threadPool = Executors.newFixedThreadPool(threads);

            final List<Future<?>> futures = new LinkedList<>();

            for (final String file : aFiles) {
                final Path trackFile = Paths.get(aPath, file);
                futures.add(threadPool.submit(new TrackReader(aMonitor, trackFile, aTracksRepo)));
            }

            final IStatus status = waitForAllTracksToBeRead(futures);

            aMonitor.done();
            return status;
        }

        private IStatus waitForAllTracksToBeRead(final List<Future<?>> futures) {
            for (final Future<?> future : futures) {
                try {
                    future.get();
                } catch (InterruptedException e) {
                    logger.log(Level.FINE, "Waiting for track to be loaded was interrupted", e);
                    Thread.currentThread().interrupt();
                    return Status.CANCEL_STATUS;
                } catch (ExecutionException e) {
                    logger.log(Level.FINE, "Reading track failed", e);
                    Thread.currentThread().interrupt();
                    return Status.CANCEL_STATUS;
                }
            }

            logger.info("Reading " + futures.size() + " tracks completed");
            return Status.OK_STATUS;
        }
    };
    job.setUser(true);
    job.schedule();
}

From source file:com.epam.catgenome.util.HistogramUtils.java

private static void addBlockToHistogram(Future<List<Wig>> future, final List<Wig> histogram) {
    try {/*from  w w  w .j a  va  2s.co  m*/
        if (future != null) {
            List<Wig> portion = future.get();
            if (portion != null) {
                histogram.addAll(portion);
            }
        }
    } catch (InterruptedException | ExecutionException e) {
        LOGGER.error("Exception while making histogram :", e);
    }
}

From source file:com.intel.cosbench.driver.service.COSBDriverService.java

private static void awaitTermination(Future<?> future) {
    try {/*from  www . ja v  a 2  s  .  c  om*/
        future.get(); // wait forever
    } catch (CancellationException ce) {
        // do nothing
    } catch (InterruptedException ie) {
        Thread.currentThread().interrupt(); // re-interrupt
    } catch (Exception ee) {
        LOGGER.error("unexcepted exception", ee);
        throw new UnexpectedException(ee); // stop execution
    }
}

From source file:io.cloudslang.content.azure.services.AuthorizationTokenImpl.java

@NotNull
public static AuthenticationResult getToken(@NotNull final AuthorizationTokenInputs inputs) throws Exception {
    final ExecutorService service = Executors.newSingleThreadExecutor();
    final AuthenticationContext context = new AuthenticationContext(inputs.getAuthority(), false, service);
    context.setProxy(getProxy(inputs.getProxyHost(), inputs.getProxyPort(), inputs.getProxyUsername(),
            inputs.getProxyPassword()));
    final Future<AuthenticationResult> future = context.acquireToken(inputs.getResource(), inputs.getClientId(),
            inputs.getUsername(), inputs.getPassword(), null);
    service.shutdown();//from  w ww.  j a  v  a  2 s.co m
    return future.get();
}

From source file:com.cloudera.impala.catalog.TestLoadHdfsMetadataPerf.java

/**
 * Test methods will call this method to list file status. Each thread will be assigned
 * the same number of tasks according to the number of partitions.
 *///from   w w w .  j  a  va2s  .  co m
private static void testMethod(MethodName methodName, String dirPath, int totalPartitionNum)
        throws InterruptedException, ExecutionException {
    String name = name(methodName.name(), dirPath);
    Timer.Context timerCtx = Metrics.INSTANCE.getTimerCtx(name);
    List<Future> futureList = new LinkedList<Future>();

    int numUnassignedPartitions = totalPartitionNum;
    int partitionsPerThread = totalPartitionNum / THREAD_NUM_PER_REQUEST;
    // When there are fewer partitions than threads, assign 1 per thread until there are
    // no partitions left.
    if (partitionsPerThread == 0) {
        partitionsPerThread = 1;
    }

    // Each thread will be assigned with the same number of partitions except when
    // partition number cannot be divisible by THREAD_NUM_PER_REQUEST, or when there are
    // less partition number than the thread number.
    for (int i = 0; i < THREAD_NUM_PER_REQUEST && numUnassignedPartitions > 0; ++i) {
        // When the partition number cannot be divisible by THREAD_NUM_PER_REQUEST, the
        // last thread will be assigned with the partitions left.
        if (i == THREAD_NUM_PER_REQUEST - 1) {
            partitionsPerThread = numUnassignedPartitions;
        }

        futureList.add(executorService_.submit(new FileStatusLoader(methodName, dirPath, partitionsPerThread)));

        numUnassignedPartitions -= partitionsPerThread;
    }

    // Block until all futures complete.
    for (Future future : futureList) {
        future.get();
    }
    LOG.info("{} : {}millisec", name, timerCtx.stop() / Metrics.NANOTOMILLISEC);
}

From source file:com.controller.CPMOrderMANIAC.java

public static List<SingleOrder> updateOrders()
        throws ExecutionException, InterruptedException, IOException, JSONException {
    String currUsername = CMAIN.reportUser().getUsername();
    HttpResponse<JsonNode> resp;/*www .j  a v  a  2 s.  c o m*/

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

    //REQUEST
    HttpGet request = new HttpGet("http://139.59.17.119:8080/api/pm/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());
    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(CPMOrderMANIAC.class.getName()).log(Level.SEVERE, null, ex);
        }
        SingleOrder currentSingleOrder = JsonParsing.parseJsonToSingleOrderObject(currentOrder.toString());
        arrayOrders.add(currentSingleOrder);
    }
    arrayOrdersMaster = arrayOrders;

    //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:net.lldp.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  . j  ava 2 s .c o m
 *
 * @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, StatusLogger logger)
        throws ChecksimsException {
    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 ChecksimsException("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, logger);
        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 ChecksimsException("Error while executing worker for future", e.getCause());
            }
        }

        return unpackInto;
    } catch (InterruptedException e) {
        executor.shutdownNow();
        throw new ChecksimsException("Execution of Checksims was interrupted!", e);
    } catch (RejectedExecutionException e) {
        executor.shutdownNow();
        throw new ChecksimsException("Could not schedule execution of all tasks!", e);
    }
}