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.amazonaws.services.kinesis.multilang.MultiLangDaemon.java

/**
 * @param args Accepts a single argument, that argument is a properties file which provides KCL configuration as
 *        well as the name of an executable.
 *///from   w w  w .  j  av a2  s  . c  o m
public static void main(String[] args) {

    if (args.length == 0) {
        printUsage(System.err, "You must provide a properties file");
        System.exit(1);
    }
    MultiLangDaemonConfig config = null;
    try {
        config = new MultiLangDaemonConfig(args[0]);
    } catch (IOException e) {
        printUsage(System.err, "You must provide a properties file");
        System.exit(1);
    } catch (IllegalArgumentException e) {
        printUsage(System.err, e.getMessage());
        System.exit(1);
    }

    ExecutorService executorService = config.getExecutorService();

    // Daemon
    MultiLangDaemon daemon = new MultiLangDaemon(config.getKinesisClientLibConfiguration(),
            config.getRecordProcessorFactory(), executorService);

    Future<Integer> future = executorService.submit(daemon);
    try {
        System.exit(future.get());
    } catch (InterruptedException | ExecutionException e) {
        LOG.error("Encountered an error while running daemon", e);
    }
    System.exit(1);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<Runnable>(48);
    ThreadPoolExecutor testExecutor = new ThreadPoolExecutor(6, 10, 1, TimeUnit.SECONDS, blockingQueue);
    List<Future<String>> futures = new ArrayList<>();
    for (int i = 0; i < 20; i++) {
        Future<String> testFuture = testExecutor.submit(new MyCallable(i));
        futures.add(testFuture);/*from   w  ww  .j  a  v  a 2 s. c o m*/
    }
    for (Future<String> testFuture : futures) {
        System.out.println("Output Returned is : " + testFuture.get());
    }
}

From source file:com.boonya.http.async.examples.nio.client.AsyncClientHttpExchangeStreaming.java

public static void main(final String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {//from w  w w. j  ava 2 s . co  m
        httpclient.start();
        Future<Boolean> future = httpclient.execute(HttpAsyncMethods.createGet("http://localhost:8080/"),
                new MyResponseConsumer(), null);
        Boolean result = future.get();
        if (result != null && result.booleanValue()) {
            System.out.println("Request successfully executed");
        } else {
            System.out.println("Request failed");
        }
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}

From source file:com.boonya.http.async.examples.nio.client.AsyncClientPipelinedStreaming.java

public static void main(final String[] args) throws Exception {
    CloseableHttpPipeliningClient httpclient = HttpAsyncClients.createPipelining();
    try {/*from   ww w.j  a  v  a  2  s . c  o  m*/
        httpclient.start();

        HttpHost targetHost = new HttpHost("localhost", 8080);
        HttpGet[] resquests = { new HttpGet("/docs/index.html"), new HttpGet("/docs/introduction.html"),
                new HttpGet("/docs/setup.html"), new HttpGet("/docs/config/index.html") };

        List<MyRequestProducer> requestProducers = new ArrayList<MyRequestProducer>();
        List<MyResponseConsumer> responseConsumers = new ArrayList<MyResponseConsumer>();
        for (HttpGet request : resquests) {
            requestProducers.add(new MyRequestProducer(targetHost, request));
            responseConsumers.add(new MyResponseConsumer(request));
        }

        Future<List<Boolean>> future = httpclient.execute(targetHost, requestProducers, responseConsumers,
                null);
        future.get();
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Path path = Paths.get("test.txt");

    try (AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE,
            StandardOpenOption.CREATE)) {
        ByteBuffer dataBuffer = getDataBuffer();
        Future<Integer> result = afc.write(dataBuffer, 0);
        while (!result.isDone()) {
            System.out.println("Sleeping for 2  seconds...");
            Thread.sleep(2000);/*from  ww  w  .  j av  a 2 s.  co  m*/
        }
        int writtenBytes = result.get();
        System.out.format("%s bytes written  to  %s%n", writtenBytes, path.toAbsolutePath());

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

public static void main(String args[]) throws Exception {
    ExecutorService executor = Executors.newCachedThreadPool();
    Future<?> future = executor.submit(() -> {
        try {/*from  www. java  2 s  .  c om*/
            Thread.sleep(1000);
        } catch (Exception e) {
            System.out.println("Epic fail.");
        }
    });
    System.out.println("Waiting for task to finish..");
    future.get();
    System.out.println("Task finished!");
    executor.shutdown();
}

From source file:com.rk.grid.federation.FederatedCluster.java

/**
 * @param args/* w w  w.ja va2s  .c  om*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    int port = Integer.parseInt(args[0]);
    String clusterName = args[1];
    String masterBrokerServiceName = args[2];
    int masterPort = Integer.parseInt(args[3]);
    String masterHost = args[4];

    IBroker<Object> masterBroker = null;
    for (int i = 0; i < 100; i++) {
        try {
            masterBroker = getConnection(masterBrokerServiceName, masterPort, masterHost);
            if (masterBroker != null)
                break;
        } catch (RemoteLookupFailureException e) {
            if (i % 100 == 0)
                System.out.println("Sleeping....");
        }
        Thread.sleep(100);
    }

    if (masterBroker == null)
        throw new RuntimeException("Unable to find master broker " + masterBrokerServiceName);

    BrokerInfo brokerInfo = masterBroker.getBrokerInfo();
    GridConfig gridConfig = brokerInfo.getConfig();
    List<String> jvmNodeParams = masterBroker.getBrokerInfo().getJvmNodeParams();
    GridExecutorService cluster = new GridExecutorService(port, jvmNodeParams, gridConfig, clusterName);
    cluster.getBroker().unPause();

    final TaskExecutor taskExecutor = new TaskExecutor(cluster);

    final IRemoteResultsHandler<Object> callback = masterBroker.getCallback();
    IWorkQueue<Object> workQueue = masterBroker.getWorkQueue();

    ExecutorService pool = Executors.newFixedThreadPool(3);

    masterBroker.unPause();

    while (!Thread.currentThread().isInterrupted()) {
        final IExecutable<?> executable = workQueue.take();

        if (executable == null)
            continue;

        if (executable.equals(IExecutable.POISON)) {
            break;
        }

        Callable<Object> callable = new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                Future<ITaskResult<?>> future = taskExecutor.submit(executable);
                ITaskResult<?> iResult = future.get();

                String uid = executable.getUID();
                try {
                    callback.accept(new RemoteResult<Object>(iResult, uid));
                } catch (Throwable t) {
                    t.printStackTrace();
                    try {
                        callback.accept(new RemoteResult<Object>(
                                new RemoteExecutorException("Error execution remote task '" + uid + "'", t),
                                uid));
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                }
                return null;
            }

        };

        pool.submit(callable);
    }
    pool.shutdown();
    taskExecutor.shutdown();
    System.out.println("Finished...!");
}

From source file:gobblin.restli.throttling.LocalStressTest.java

public static void main(String[] args) throws Exception {

    CommandLine cli = StressTestUtils.parseCommandLine(OPTIONS, args);

    int stressorThreads = Integer.parseInt(
            cli.getOptionValue(STRESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_STRESSOR_THREADS)));
    int processorThreads = Integer.parseInt(
            cli.getOptionValue(PROCESSOR_THREADS.getOpt(), Integer.toString(DEFAULT_PROCESSOR_THREADS)));
    int artificialLatency = Integer.parseInt(
            cli.getOptionValue(ARTIFICIAL_LATENCY.getOpt(), Integer.toString(DEFAULT_ARTIFICIAL_LATENCY)));
    long targetQps = Integer.parseInt(cli.getOptionValue(QPS.getOpt(), Integer.toString(DEFAULT_TARGET_QPS)));

    Configuration configuration = new Configuration();
    StressTestUtils.populateConfigFromCli(configuration, cli);

    String resourceLimited = LocalStressTest.class.getSimpleName();

    Map<String, String> configMap = Maps.newHashMap();

    ThrottlingPolicyFactory factory = new ThrottlingPolicyFactory();
    SharedLimiterKey res1key = new SharedLimiterKey(resourceLimited);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null,
            ThrottlingPolicyFactory.POLICY_KEY), QPSPolicy.FACTORY_ALIAS);
    configMap.put(BrokerConfigurationKeyGenerator.generateKey(factory, res1key, null, QPSPolicy.QPS),
            Long.toString(targetQps));

    ThrottlingGuiceServletConfig guiceServletConfig = new ThrottlingGuiceServletConfig();
    guiceServletConfig.initialize(ConfigFactory.parseMap(configMap));
    LimiterServerResource limiterServer = guiceServletConfig.getInjector()
            .getInstance(LimiterServerResource.class);

    RateComputingLimiterContainer limiterContainer = new RateComputingLimiterContainer();

    Class<? extends Stressor> stressorClass = configuration.getClass(StressTestUtils.STRESSOR_CLASS,
            StressTestUtils.DEFAULT_STRESSOR_CLASS, Stressor.class);

    ExecutorService executorService = Executors.newFixedThreadPool(stressorThreads);

    SharedResourcesBroker broker = guiceServletConfig.getInjector().getInstance(
            Key.get(SharedResourcesBroker.class, Names.named(LimiterServerResource.BROKER_INJECT_NAME)));
    ThrottlingPolicy policy = (ThrottlingPolicy) broker.getSharedResource(new ThrottlingPolicyFactory(),
            new SharedLimiterKey(resourceLimited));
    ScheduledExecutorService reportingThread = Executors.newSingleThreadScheduledExecutor();
    reportingThread.scheduleAtFixedRate(new Reporter(limiterContainer, policy), 0, 15, TimeUnit.SECONDS);

    Queue<Future<?>> futures = new LinkedList<>();
    MockRequester requester = new MockRequester(limiterServer, artificialLatency, processorThreads);

    requester.start();//from  w  ww  . j  a  v  a 2 s .com
    for (int i = 0; i < stressorThreads; i++) {
        RestliServiceBasedLimiter restliLimiter = RestliServiceBasedLimiter.builder()
                .resourceLimited(resourceLimited).requestSender(requester).serviceIdentifier("stressor" + i)
                .build();

        Stressor stressor = stressorClass.newInstance();
        stressor.configure(configuration);
        futures.add(executorService
                .submit(new StressorRunner(limiterContainer.decorateLimiter(restliLimiter), stressor)));
    }
    int stressorFailures = 0;
    for (Future<?> future : futures) {
        try {
            future.get();
        } catch (ExecutionException ee) {
            stressorFailures++;
        }
    }
    requester.stop();

    executorService.shutdownNow();

    if (stressorFailures > 0) {
        log.error("There were " + stressorFailures + " failed stressor threads.");
    }
    System.exit(stressorFailures);
}

From source file:com.alibaba.dubbo.examples.async.AsyncConsumer.java

public static void main(String[] args) throws Exception {
    String config = AsyncConsumer.class.getPackage().getName().replace('.', '/') + "/async-consumer.xml";
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(config);
    context.start();/*from  w ww  .jav a  2  s. c  o m*/

    final AsyncService asyncService = (AsyncService) context.getBean("asyncService");

    Future<String> f = RpcContext.getContext().asyncCall(new Callable<String>() {
        public String call() throws Exception {
            return asyncService.sayHello("async call request");
        }
    });

    System.out.println("async call ret :" + f.get());

    RpcContext.getContext().asyncCall(new Runnable() {
        public void run() {
            asyncService.sayHello("oneway call request1");
            asyncService.sayHello("oneway call request2");
        }
    });

    System.in.read();
}

From source file:com.boonya.http.async.examples.nio.client.AsyncClientCustomContext.java

public final static void main(String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {//from ww  w  .j ava 2 s. c o m
        // Create a local instance of cookie store
        CookieStore cookieStore = new BasicCookieStore();

        // Create local HTTP context
        HttpClientContext localContext = HttpClientContext.create();
        // Bind custom cookie store to the local context
        localContext.setCookieStore(cookieStore);

        HttpGet httpget = new HttpGet("http://localhost/");
        System.out.println("Executing request " + httpget.getRequestLine());

        httpclient.start();

        // Pass local context as a parameter
        Future<HttpResponse> future = httpclient.execute(httpget, localContext, null);

        // Please note that it may be unsafe to access HttpContext instance
        // while the request is still being executed

        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("Local cookie: " + cookies.get(i));
        }
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}