Example usage for java.util.concurrent Callable Callable

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

Introduction

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

Prototype

Callable

Source Link

Usage

From source file:com.parse.CacheQueryController.java

/**
 * Retrieves the results of the last time {@link ParseQuery#count()} was called on a query
 * identical to this one.//from w  w w .j  a  v a2s  .  com
 *
 * @param sessionToken The user requesting access.
 * @return A list of {@link ParseObject}s corresponding to this query. Returns null if there is no
 *          cache for this query.
 */
private <T extends ParseObject> Task<Integer> countFromCacheAsync(final ParseQuery.State<T> state,
        String sessionToken) {
    final String cacheKey = ParseRESTQueryCommand.countCommand(state, sessionToken).getCacheKey();
    return Task.call(new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            JSONObject cached = ParseKeyValueCache.jsonFromKeyValueCache(cacheKey, state.maxCacheAge());
            if (cached == null) {
                throw new ParseException(ParseException.CACHE_MISS, "results not cached");
            }
            try {
                return cached.getInt("count");
            } catch (JSONException e) {
                throw new ParseException(ParseException.CACHE_MISS, "the cache contains corrupted json");
            }
        }
    }, Task.BACKGROUND_EXECUTOR);
}

From source file:com.microsoft.azure.management.resources.ProviderOperationsImpl.java

/**
* Gets a resource provider.//from www  .j  av  a2  s . co  m
*
* @param resourceProviderNamespace Required. Namespace of the resource
* provider.
* @return Resource provider information.
*/
@Override
public Future<ProviderGetResult> getAsync(final String resourceProviderNamespace) {
    return this.getClient().getExecutorService().submit(new Callable<ProviderGetResult>() {
        @Override
        public ProviderGetResult call() throws Exception {
            return get(resourceProviderNamespace);
        }
    });
}

From source file:com.alibaba.otter.manager.biz.monitor.impl.GlobalMonitor.java

private void concurrentProcess(Map<Long, List<AlarmRule>> rules) {
    ExecutorCompletionService completionExecutor = new ExecutorCompletionService(executor);
    List<Future> futures = new ArrayList<Future>();
    for (Entry<Long, List<AlarmRule>> entry : rules.entrySet()) {
        final List<AlarmRule> alarmRules = entry.getValue();
        futures.add(completionExecutor.submit(new Callable<Object>() {

            @Override//from w ww. j  ava 2s .  c o  m
            public Object call() throws Exception {
                pipelineMonitor.explore(alarmRules);
                return null;
            }
        }));
    }

    List<Throwable> exceptions = new ArrayList<Throwable>();
    int index = 0;
    int size = futures.size();
    while (index < size) {
        try {
            Future<?> future = completionExecutor.take();
            future.get();
        } catch (InterruptedException e) {
            exceptions.add(e);
        } catch (ExecutionException e) {
            exceptions.add(e);
        }
        index++;
    }

    if (!exceptions.isEmpty()) {
        StringBuilder sb = new StringBuilder(exceptions.size() + " exception happens in global monitor\n");
        sb.append("exception stack start :\n");
        for (Throwable t : exceptions) {
            sb.append(ExceptionUtils.getStackTrace(t));
        }
        sb.append("exception stack end \n");
        throw new IllegalStateException(sb.toString());
    }
}

From source file:com.metamx.druid.indexing.coordinator.ForkingTaskRunner.java

@Override
public ListenableFuture<TaskStatus> run(final Task task) {
    synchronized (tasks) {
        if (!tasks.containsKey(task.getId())) {
            tasks.put(task.getId(), new ForkingTaskRunnerWorkItem(task, exec.submit(new Callable<TaskStatus>() {
                @Override//from  ww  w.j  av a 2  s. c  om
                public TaskStatus call() {
                    final String attemptUUID = UUID.randomUUID().toString();
                    final File taskDir = new File(config.getBaseTaskDir(), task.getId());
                    final File attemptDir = new File(taskDir, attemptUUID);

                    final ProcessHolder processHolder;

                    try {
                        final Closer closer = Closer.create();
                        try {
                            if (!attemptDir.mkdirs()) {
                                throw new IOException(
                                        String.format("Could not create directories: %s", attemptDir));
                            }

                            final File taskFile = new File(attemptDir, "task.json");
                            final File statusFile = new File(attemptDir, "status.json");
                            final File logFile = new File(attemptDir, "log");

                            // time to adjust process holders
                            synchronized (tasks) {
                                final ForkingTaskRunnerWorkItem taskWorkItem = tasks.get(task.getId());

                                if (taskWorkItem.shutdown) {
                                    throw new IllegalStateException("Task has been shut down!");
                                }

                                if (taskWorkItem == null) {
                                    throw new ISE("WTF?! TaskInfo disappeared for task: %s", task.getId());
                                }

                                if (taskWorkItem.processHolder != null) {
                                    throw new ISE("WTF?! TaskInfo already has a process holder for task: %s",
                                            task.getId());
                                }

                                final List<String> command = Lists.newArrayList();
                                final int childPort = findUnusedPort();
                                final String childHost = String.format(config.getHostPattern(), childPort);

                                command.add(config.getJavaCommand());
                                command.add("-cp");
                                command.add(config.getJavaClasspath());

                                Iterables.addAll(command, Splitter.on(CharMatcher.WHITESPACE).omitEmptyStrings()
                                        .split(config.getJavaOptions()));

                                for (String propName : props.stringPropertyNames()) {
                                    for (String allowedPrefix : config.getAllowedPrefixes()) {
                                        if (propName.startsWith(allowedPrefix)) {
                                            command.add(String.format("-D%s=%s", propName,
                                                    props.getProperty(propName)));
                                        }
                                    }
                                }

                                // Override child JVM specific properties
                                for (String propName : props.stringPropertyNames()) {
                                    if (propName.startsWith(CHILD_PROPERTY_PREFIX)) {
                                        command.add(String.format("-D%s=%s",
                                                propName.substring(CHILD_PROPERTY_PREFIX.length()),
                                                props.getProperty(propName)));
                                    }
                                }

                                String nodeType = task.getNodeType();
                                if (nodeType != null) {
                                    command.add(String.format("-Ddruid.executor.nodeType=%s", nodeType));
                                }

                                command.add(String.format("-Ddruid.host=%s", childHost));
                                command.add(String.format("-Ddruid.port=%d", childPort));

                                command.add(config.getMainClass());
                                command.add(taskFile.toString());
                                command.add(statusFile.toString());

                                jsonMapper.writeValue(taskFile, task);

                                log.info("Running command: %s", Joiner.on(" ").join(command));
                                taskWorkItem.processHolder = new ProcessHolder(
                                        new ProcessBuilder(ImmutableList.copyOf(command))
                                                .redirectErrorStream(true).start(),
                                        logFile, childPort);

                                processHolder = taskWorkItem.processHolder;
                                processHolder.registerWithCloser(closer);
                            }

                            log.info("Logging task %s output to: %s", task.getId(), logFile);

                            final InputStream fromProc = processHolder.process.getInputStream();
                            final OutputStream toLogfile = closer
                                    .register(Files.newOutputStreamSupplier(logFile).getOutput());

                            boolean runFailed = true;

                            ByteStreams.copy(fromProc, toLogfile);
                            final int statusCode = processHolder.process.waitFor();
                            log.info("Process exited with status[%d] for task: %s", statusCode, task.getId());

                            if (statusCode == 0) {
                                runFailed = false;
                            }

                            // Upload task logs

                            // XXX: Consider uploading periodically for very long-lived tasks to prevent
                            // XXX: bottlenecks at the end or the possibility of losing a lot of logs all
                            // XXX: at once.

                            taskLogPusher.pushTaskLog(task.getId(), logFile);

                            if (!runFailed) {
                                // Process exited successfully
                                return jsonMapper.readValue(statusFile, TaskStatus.class);
                            } else {
                                // Process exited unsuccessfully
                                return TaskStatus.failure(task.getId());
                            }
                        } catch (Throwable t) {
                            throw closer.rethrow(t);
                        } finally {
                            closer.close();
                        }
                    } catch (Exception e) {
                        log.info(e, "Exception caught during execution");
                        throw Throwables.propagate(e);
                    } finally {
                        try {
                            synchronized (tasks) {
                                final ForkingTaskRunnerWorkItem taskWorkItem = tasks.remove(task.getId());
                                if (taskWorkItem != null && taskWorkItem.processHolder != null) {
                                    taskWorkItem.processHolder.process.destroy();
                                }
                            }

                            log.info("Removing temporary directory: %s", attemptDir);
                            FileUtils.deleteDirectory(attemptDir);
                        } catch (Exception e) {
                            log.error(e, "Suppressing exception caught while cleaning up task");
                        }
                    }
                }
            })));
        }

        return tasks.get(task.getId()).getResult();
    }
}

From source file:org.apache.cxf.dosgi.systests.common.rest.AbstractListenerHookServiceListenerTest.java

public void testBasicInvocation() throws Exception {

    Thread.currentThread().setContextClassLoader(JAXRSClientFactoryBean.class.getClassLoader());
    bundleContext.registerService(new String[] { "javax.ws.rs.ext.MessageBodyReader" },
            new AegisElementProvider(), new Hashtable());
    Server server1 = null;/*  w  ww . j a  va2 s. c om*/
    Server server2 = null;
    ServiceTracker tracker = null;
    try {
        server1 = startServer(ADDRESS1, GreeterService.class, new GreeterServiceImpl());

        server2 = startServer(ADDRESS2, GreeterService.class, new GreeterServiceImpl());
        tracker = new ServiceTracker(bundleContext, GreeterService.class.getName(), null) {
            @Override
            public Object addingService(final ServiceReference reference) {
                Object result = super.addingService(reference);

                FutureTask<GreeterInfo> future = new FutureTask<GreeterInfo>(new Callable<GreeterInfo>() {
                    public GreeterInfo call() {
                        return useService(reference);
                    }
                });
                future.run();
                synchronized (mutex1) {
                    synchronized (mutex2) {
                        if (task1 == null) {
                            task1 = future;
                            mutex1.notify();
                        } else if (task2 == null) {
                            task2 = future;
                            mutex2.notify();
                        }
                    }
                }
                return result;
            }
        };
        tracker.open();
        // sleep for a bit
        Thread.sleep(2000);

        installDswIfNeeded();

        verifyGreeterResponse(task1, mutex1);
        verifyGreeterResponse(task2, mutex2);
    } finally {
        if (tracker != null) {
            tracker.close();
        }

        if (server1 != null) {
            server1.getDestination().shutdown();
            server1.stop();
        }

        if (server2 != null) {
            server2.getDestination().shutdown();
            server2.stop();
        }

    }
}

From source file:de.btobastian.javacord.entities.impl.ImplCustomEmoji.java

@Override
public Future<byte[]> getEmojiAsByteArray(FutureCallback<byte[]> callback) {
    ListenableFuture<byte[]> future = api.getThreadPool().getListeningExecutorService()
            .submit(new Callable<byte[]>() {
                @Override//from w  w  w . j a  v a2s . c  o m
                public byte[] call() throws Exception {
                    logger.debug("Trying to get emoji {} from server {}", ImplCustomEmoji.this, server);
                    URL url = getImageUrl();
                    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
                    conn.setRequestProperty("User-Agent", Javacord.USER_AGENT);
                    InputStream in = new BufferedInputStream(conn.getInputStream());
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    byte[] buf = new byte[1024];
                    int n;
                    while (-1 != (n = in.read(buf))) {
                        out.write(buf, 0, n);
                    }
                    out.close();
                    in.close();
                    byte[] emoji = out.toByteArray();
                    logger.debug("Got emoji {} from server {} (size: {})", ImplCustomEmoji.this, server,
                            emoji.length);
                    return emoji;
                }
            });
    if (callback != null) {
        Futures.addCallback(future, callback);
    }
    return future;
}

From source file:com.atomicleopard.thundr.ftp.FtpSession.java

public boolean deleteFile(final String file) {
    return timeLogAndCatch("Delete file", new Callable<Boolean>() {
        @Override//from   w ww .  j av a 2  s .c  om
        public Boolean call() throws Exception {
            return preparedClient.deleteFile(file);
        }
    });
}

From source file:io.github.mmichaelis.selenium.client.provider.AbstractWebDriverProviderTest.java

@Test
public void retrieving_webdriver_twice_returns_same_instance_on_thread() throws Exception {
    final WebDriverProvider driverProvider = new NoExceptionWebDriverProvider(defaultDriver, otherDriver);
    final Future<WebDriver[]> webDriversFuture = Executors.newCachedThreadPool()
            .submit(new Callable<WebDriver[]>() {
                @Override/*w  w w . j a  va2  s . co m*/
                public WebDriver[] call() {
                    return new WebDriver[] { driverProvider.get(), driverProvider.get() };
                }
            });
    final WebDriver[] webDrivers = webDriversFuture.get();
    assertThat(defaultDriver, sameInstance(webDrivers[0]));
    assertThat(defaultDriver, sameInstance(webDrivers[1]));
}

From source file:org.chromium.android_webview.test.AwContentsTest.java

@LargeTest
@Feature({ "AndroidWebView" })
public void testCreateAndGcManyTimes() throws Throwable {
    final int CONCURRENT_INSTANCES = 4;
    final int REPETITIONS = 16;
    // The system retains a strong ref to the last focused view (in InputMethodManager)
    // so allow for 1 'leaked' instance.
    final int MAX_IDLE_INSTANCES = 1;

    System.gc();/*from  w  w w  .  j  a  v  a 2s . c  om*/

    pollOnUiThread(new Callable<Boolean>() {
        @Override
        public Boolean call() {
            return AwContents.getNativeInstanceCount() <= MAX_IDLE_INSTANCES;
        }
    });
    for (int i = 0; i < REPETITIONS; ++i) {
        for (int j = 0; j < CONCURRENT_INSTANCES; ++j) {
            AwTestContainerView view = createAwTestContainerViewOnMainSync(mContentsClient);
            loadUrlAsync(view.getAwContents(), "about:blank");
        }
        assertTrue(AwContents.getNativeInstanceCount() >= CONCURRENT_INSTANCES);
        assertTrue(AwContents.getNativeInstanceCount() <= (i + 1) * CONCURRENT_INSTANCES);
        runTestOnUiThread(new Runnable() {
            @Override
            public void run() {
                getActivity().removeAllViews();
            }
        });
    }

    System.gc();

    pollOnUiThread(new Callable<Boolean>() {
        @Override
        public Boolean call() {
            return AwContents.getNativeInstanceCount() <= MAX_IDLE_INSTANCES;
        }
    });
}