Example usage for java.util.concurrent Callable call

List of usage examples for java.util.concurrent Callable call

Introduction

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

Prototype

V call() throws Exception;

Source Link

Document

Computes a result, or throws an exception if unable to do so.

Usage

From source file:org.fishwife.jrugged.spring.retry.ExtendedRetryTemplateTest.java

@Test
public void test_execute_callable() throws Exception {
    Callable<Long> callable = Mockito.mock(Callable.class);
    ExtendedRetryTemplate template = new ExtendedRetryTemplate();

    Mockito.when(callable.call()).thenReturn(10L);

    Assert.assertEquals(10L, template.execute(callable).longValue());

    Mockito.verify(callable, Mockito.times(1)).call();

}

From source file:io.airlift.stats.TimeStat.java

public <T> T time(Callable<T> callable) throws Exception {
    long start = ticker.read();
    T result = callable.call();
    add(ticker.read() - start);/*  w w w . java 2  s. co m*/
    return result;
}

From source file:io.ecarf.core.cloud.task.processor.files.ProcessFilesTask.java

@Override
public void run() throws IOException {

    log.info("START: processing files");

    Stopwatch stopwatch = Stopwatch.createStarted();

    Set<String> filesSet = ObjectUtils.csvToSet(files);
    log.info("Processing files: " + filesSet);

    List<Callable<T>> tasks = getSubTasks(filesSet);

    int processors = Runtime.getRuntime().availableProcessors();

    try {//from ww  w. j  a  va 2s. com

        // check if we only have one file to process
        if (tasks.size() == 1) {

            this.processSingleOutput(tasks.get(0).call());

        } else if (processors == 1) {
            // only one process then process synchronously
            List<T> output = new ArrayList<>();
            for (Callable<T> task : tasks) {
                output.add(task.call());
            }

            this.processMultiOutput(output);

        } else {

            // multiple cores
            ExecutorService executor = Utils.createFixedThreadPool(processors);

            try {

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

                for (Future<T> result : results) {
                    output.add(result.get());
                }

                this.processMultiOutput(output);

            } finally {
                executor.shutdown();
            }
        }

    } catch (Exception e) {
        log.error("Failed to process multiple files", e);
        throw new IOException(e);

    }

    log.info("TIMER# All files are processed successfully, elapsed time: " + stopwatch);
}

From source file:org.springframework.boot.StartupInfoLogger.java

private String getValue(String prefix, Callable<Object> call, String defaultValue) {
    try {/*from   www.java 2s  .c  o m*/
        Object value = call.call();
        if (value != null && StringUtils.hasLength(value.toString())) {
            return prefix + value;
        }
    } catch (Exception ex) {
        // Swallow and continue
    }
    return defaultValue;
}

From source file:org.apache.hadoop.hive.ql.exec.mr.ObjectCache.java

@Override
public <T> T retrieve(String key, Callable<T> fn) throws HiveException {
    try {/*from   ww  w . j a  v  a2 s.co m*/
        if (isInfoEnabled) {
            LOG.info("Creating " + key);
        }
        return fn.call();
    } catch (Exception e) {
        throw new HiveException(e);
    }
}

From source file:com.netflix.nicobar.example.groovy2.GroovyModuleLoaderExample.java

public void runExample() throws Exception {

    // create the loader with the groovy plugin
    ScriptModuleLoader moduleLoader = new ScriptModuleLoader.Builder()
            .addPluginSpec(new ScriptCompilerPluginSpec.Builder(GROOVY2_PLUGIN_ID) // configure Groovy plugin
                    .addRuntimeResource(ExampleResourceLocator.getGroovyRuntime())
                    .addRuntimeResource(ExampleResourceLocator.getGroovyPluginLocation())
                    .withPluginClassName(GROOVY2_COMPILER_PLUGIN_CLASS).build())
            .addListener(new BaseScriptModuleListener() { // add an example listener for module updates
                public void moduleUpdated(ScriptModule newScriptModule, ScriptModule oldScriptModule) {
                    System.out.printf("Received module update event. newModule: %s,  oldModule: %s%n",
                            newScriptModule, oldScriptModule);
                }//from   www. ja v  a2  s  . c o m
            }).build();

    // create an archive repository and wrap a poller around it to feed updates to the module loader
    Path baseArchiveDir = Files.createTempDirectory(GroovyModuleLoaderExample.class.getSimpleName());
    JarArchiveRepository repository = new JarArchiveRepository.Builder(baseArchiveDir).build();
    deployTestArchive(repository);
    ArchiveRepositoryPoller poller = new ArchiveRepositoryPoller.Builder(moduleLoader).build();
    poller.addRepository(repository, 30, TimeUnit.SECONDS, true);

    // the test module has now been compiled and is ready for execution.
    // create a closure which knows how to bind any request time inputs (if any) and execute the module.
    ScriptModuleExecutable<String> executable = new ScriptModuleExecutable<String>() {
        @Override
        public String execute(ScriptModule scriptModule) throws Exception {
            // the script doesn't necessarily have to implement any specific interfaces, but it does need to
            // be compilable to a class.
            Class<?> callable = ScriptModuleUtils.findAssignableClass(scriptModule, Callable.class);
            @SuppressWarnings("unchecked")
            Callable<String> instance = (Callable<String>) callable.newInstance();
            String result = instance.call();
            return result;
        }
    };

    // Execute it in a Hystrix command.
    HystrixScriptModuleExecutor<String> executor = new HystrixScriptModuleExecutor<String>(
            "TestModuleExecutor");
    List<String> results = executor.executeModules(Collections.singletonList(SCRIPT_MODULE_ID), executable,
            moduleLoader);
    System.out.println("Module(s) have been executed. Output: " + results);

    // release the Hystrix resources
    Hystrix.reset();
}

From source file:com.proofpoint.stats.TimeStat.java

public <T> T time(Callable<T> callable) throws Exception {
    try (BlockTimer ignored = time()) {
        return callable.call();
    }/*from w w  w .  j a va 2s  .  c o  m*/
}

From source file:com.zaubersoftware.gnip4j.http.ReconnectionTest.java

@Override
public <T> Future<T> submit(final Callable<T> task) {
    try {/*from   ww w . ja va2s.  com*/
        task.call();
    } catch (final Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:org.apache.hive.beeline.QFileBeeLineClient.java

public void execute(QFile qFile, List<Callable<Void>> preCommands) throws Exception {
    if (preCommands == null) {
        preCommands = new ArrayList<Callable<Void>>();
    }/* ww w .j  ava  2  s. co m*/

    beforeExecute(qFile);

    for (Callable<Void> c : preCommands) {
        c.call();
    }

    String[] commands = beeLine.getCommands(qFile.getInputFile());
    execute(qFile.filterCommands(commands), qFile.getRawOutputFile(), qFile.getConverter());
    afterExecute(qFile);
}

From source file:org.apache.hadoop.hive.ql.exec.tez.ObjectCache.java

@SuppressWarnings("unchecked")
@Override//from w  ww.j  a va2 s.c o  m
public <T> T retrieve(String key, Callable<T> fn) throws HiveException {
    T value;
    try {
        value = (T) registry.get(key);
        if (value == null) {
            value = fn.call();
            LOG.info("Caching key: " + key);
            registry.cacheForVertex(key, value);
        } else {
            LOG.info("Found " + key + " in cache with value: " + value);
        }
    } catch (Exception e) {
        throw new HiveException(e);
    }
    return value;
}