Example usage for java.util.concurrent FutureTask FutureTask

List of usage examples for java.util.concurrent FutureTask FutureTask

Introduction

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

Prototype

public FutureTask(Callable<V> callable) 

Source Link

Document

Creates a FutureTask that will, upon running, execute the given Callable .

Usage

From source file:com.basho.riak.client.raw.pbc.PBMapReduceResult.java

/**
 * @param response/*from  w w  w.  j  a v a2 s. c  o  m*/
 */
private PBMapReduceResult(final MapReduceResponseSource response) {
    this.objectMapper = new ObjectMapper();

    // Getting the actual result from PB stream must be run once only
    rawResultTask = new FutureTask<String>(new Callable<String>() {

        public String call() throws Exception {
            JSONArray results = MapReduceResponseSource.readAllResults(response);
            return results.toString();
        }
    });
}

From source file:android.support.test.espresso.base.ThreadPoolExecutorExtractor.java

public ThreadPoolExecutor getAsyncTaskThreadPool() {
    FutureTask<Optional<ThreadPoolExecutor>> getTask = null;
    if (Build.VERSION.SDK_INT < 11) {
        getTask = new FutureTask<Optional<ThreadPoolExecutor>>(LEGACY_ASYNC_TASK_EXECUTOR);
    } else {//from   ww  w.j  a  va2s. co m
        getTask = new FutureTask<Optional<ThreadPoolExecutor>>(POST_HONEYCOMB_ASYNC_TASK_EXECUTOR);
    }

    try {
        return runOnMainThread(getTask).get().get();
    } catch (InterruptedException ie) {
        throw new RuntimeException("Interrupted while trying to get the async task executor!", ie);
    } catch (ExecutionException ee) {
        throw new RuntimeException(ee.getCause());
    }
}

From source file:com.github.gregwhitaker.asyncshowdown.HelloController.java

/**
 * Asynchronously waits a random random number of milliseconds, within the specified minimum and maximum, before
 * returning a 200 HTTP response with the body containing the string "Hello World!"
 *
 * @param minSleep minimum sleep time in milliseconds
 * @param maxSleep maximum sleep time in milliseconds
 * @return A 200 HTTP response with the body containing the string "Hello World!"
 *//*w ww.j a  v  a  2s .com*/
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public DeferredResult<ResponseEntity<String>> hello(
        @RequestParam(name = "minSleepMs", defaultValue = "500") long minSleep,
        @RequestParam(name = "maxSleepMs", defaultValue = "500") long maxSleep) {
    final DeferredResult<ResponseEntity<String>> deferredResult = new DeferredResult<>();

    final FutureTask<String> helloTask = new FutureTask(new HelloGenerator(minSleep, maxSleep));
    Observable.<String>create(sub -> {
        String message = null;
        try {
            helloTask.run();
            message = helloTask.get();
        } catch (Exception e) {
            sub.onError(e);
        }
        sub.onNext(message);
        sub.onCompleted();
    }).last().subscribeOn(Schedulers.io()).subscribe(
            message -> deferredResult.setResult(ResponseEntity.ok(message)),
            error -> deferredResult.setResult(ResponseEntity.status(500).body(error.getMessage())));

    return deferredResult;
}

From source file:org.rhq.enterprise.server.configuration.LiveConfigurationLoader.java

/**
 *
 * @param resources/*from   w  w w  . j  a  v a 2s  .  co  m*/
 * @param timeout the number of seconds before this call should timeout and
 * @return
 * @throws Exception
 */
public Map<Integer, Configuration> loadLiveResourceConfigurations(final Set<Resource> resources, long timeout) {
    try {
        FutureTask<Map<Integer, Configuration>> task = new FutureTask<Map<Integer, Configuration>>(
                new Callable<Map<Integer, Configuration>>() {
                    public Map<Integer, Configuration> call() throws Exception {
                        return loadLiveResourceConfigurations(resources);
                    }
                });
        new Thread(task).start();
        return task.get(timeout, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        throw new RuntimeException(
                "Timed out after " + timeout + " seconds while retrieving live Resource configurations.");
    } catch (Exception e) {
        throw new RuntimeException("Failed to retrieve live Resource configurations.", e);
    }
}

From source file:com.mellanox.jxio.tests.benchmarks.DataPathTestClient.java

public DataPathTestClient(String[] args) {
    super(args);/*  www  .  j a v  a  2 s.  c o  m*/
    test_iterations = Integer.parseInt(args[7]);
    file_path = args[6];
    results = new double[num_of_threads][test_iterations * 3];
    workers = new ArrayList<FutureTask<double[]>>(num_of_threads);
    executor = Executors.newFixedThreadPool(num_of_threads);

    for (int i = 0; i < num_of_threads; i++) {
        ClientWorker cw = new ClientWorker(inMsg_size, outMsg_size, uri, burst_size, results[i]);
        workers.add(new FutureTask<double[]>(cw));
    }
    // Create/Open file
    if (!file_path.equals("no_file")) {
        write_to_file = true;
        try {
            fstream = new FileWriter(file_path, true);
            out = new BufferedWriter(fstream);
        } catch (Exception e) {
            LOG.error("Error in opening the results file");
            e.printStackTrace();
        }
    }
}

From source file:com.google.code.jconfig.factory.ConfigurationPluginFactory.java

/**
 * <p>/*  w w w .j a  va2 s . co m*/
 *    Returns a plugin instance of type <em>classname</em>.
 * </p>
 * 
 * <p>
 *    If the implementation class use the {@link Cacheable} annotation, it
 *    will be cached for future reuse otherwise a new instance will be
 *    created at every request.
 * </p>
 * 
 * @param classname the full name of an instance of
 *                  {@link IConfigurationPlugin}.
 * @return the plugin instance.
 * @throws PluginInstantiationException
 */
public static IConfigurationPlugin<?> getPlugin(final String classname) throws PluginInstantiationException {

    try {
        if (ClassUtils.getClass(classname).getAnnotation(Cacheable.class) == null) {
            logger.debug("Plugin <" + classname + "> is not cacheable. Creating a new one.");
            return (IConfigurationPlugin<?>) Class.forName(classname).newInstance();
        }
    } catch (Exception e) {
        throw new PluginInstantiationException(e.getMessage(), e);
    }

    // cacheable plugin
    FutureTask<IConfigurationPlugin<?>> theTask = cache.get(classname);
    if (theTask == null) {
        logger.debug("No plugin of class <" + classname + "> available. Creatine a new one.");
        Callable<IConfigurationPlugin<?>> eval = new Callable<IConfigurationPlugin<?>>() {

            public IConfigurationPlugin<?> call() throws Exception {
                IConfigurationPlugin<?> plugin = (IConfigurationPlugin<?>) Class.forName(classname)
                        .newInstance();
                return plugin;
            }
        };

        FutureTask<IConfigurationPlugin<?>> thePluginExec = new FutureTask<IConfigurationPlugin<?>>(eval);
        theTask = cache.putIfAbsent(classname, thePluginExec);
        if (theTask == null) {
            theTask = thePluginExec;
            theTask.run();
        }
        logger.debug("New plugin of class <" + classname + "> ready to be used and cached.");
    } else {
        logger.debug("Plugin of class <" + classname + "> available in cache. Using the cached one.");
    }

    try {
        return theTask.get();
    } catch (Exception e) {
        throw new PluginInstantiationException(e.getMessage(), e);
    } finally {
        logger.debug("plugin cache size: " + cache.size() + " - cache detail: " + cache);
    }
}

From source file:net.pms.io.ByteProcessWrapperConsumer.java

@Override
@Nullable/*  w ww.  j av  a2 s. c o m*/
public FutureTask<byte[]> consume(@Nullable final InputStream inputStream, @Nullable String threadName) {
    if (inputStream == null) {
        return null;
    }
    Callable<byte[]> callable = new Callable<byte[]>() {

        @Override
        public byte[] call() throws Exception {
            byte[] result = IOUtils.toByteArray(inputStream);
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Captured {} bytes of process output", result.length);
            }
            return result;
        }
    };
    FutureTask<byte[]> result = new FutureTask<byte[]>(callable);
    Thread runner;
    if (isBlank(threadName)) {
        runner = new Thread(result);
    } else {
        runner = new Thread(result, threadName);
    }
    runner.start();
    return result;
}

From source file:Main.java

/**
 * Run the supplied Callable on the main thread. The method will block only if the current
 * thread is the main thread./*from ww w  .ja v a  2s . co m*/
 *
 * @param c The Callable to run
 * @return A FutureTask wrapping the callable to retrieve results
 */
public static <T> FutureTask<T> runOnUiThread(Callable<T> c) {
    return runOnUiThread(new FutureTask<T>(c));
}

From source file:ubic.gemma.core.loader.util.fetcher.FtpFetcher.java

protected FutureTask<Boolean> defineTask(final String outputFileName, final String seekFile) {
    return new FutureTask<>(new Callable<Boolean>() {
        @Override//from   www .  ja v  a2s.  c  om
        public Boolean call() throws IOException {
            File existing = new File(outputFileName);
            if (existing.exists() && avoidDownload) {
                log.info("A local file exists, skipping download.");
                ftpClient.disconnect();
                return Boolean.TRUE;
            } else if (existing.exists() && allowUseExisting) {
                log.info("Checking validity of existing local file: " + outputFileName);
            } else {
                log.info("Fetching " + seekFile + " to " + outputFileName);
            }
            boolean status = NetUtils.ftpDownloadFile(ftpClient, seekFile, outputFileName, force);
            ftpClient.disconnect();
            return status;
        }
    });
}

From source file:pl.nask.hsn2.service.CachingTemplateRegistry.java

final String getTemplateUsingCache(final String templateName) throws ResourceException {
    Future<String> f = templates.get(templateName);
    if (f == null) {
        FutureTask<String> future = new FutureTask<String>(new Callable<String>() {

            @Override//w w w . ja v  a 2  s  .c o  m
            public String call() throws ResourceException {
                return readFileAsString(templateName);
            }
        });
        f = templates.putIfAbsent(templateName, future);
        if (f == null) {
            f = future;
            future.run();
        }
    }

    try {
        return f.get();
    } catch (InterruptedException e) {
        throw new ResourceException("Interrupted while waiting for the resource", e);
    } catch (ExecutionException e) {
        throw new ResourceException("Exception while producing the resource", e);
    }
}