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.FileObjectStore.java

@Override
public Task<Boolean> existsAsync() {
    return Task.call(new Callable<Boolean>() {
        @Override//from   w  ww .  jav  a  2  s .c o  m
        public Boolean call() throws Exception {
            return file.exists();
        }
    }, ParseExecutors.io());
}

From source file:net.eusashead.hateoas.response.argumentresolver.AsyncEntityController.java

@RequestMapping(method = RequestMethod.DELETE)
public Callable<ResponseEntity<Void>> delete(@PathVariable final String name,
        final DeleteResponseBuilder builder) {

    return new Callable<ResponseEntity<Void>>() {

        @Override//w w w.j a v  a2  s.c o  m
        public ResponseEntity<Void> call() throws Exception {
            service.delete(name);
            return builder.build();
        }
    };
}

From source file:pt.webdetails.cpf.messaging.BeanyPluginCall.java

Callable<String> asCallable(final Map<String, String[]> parameters) {
    return new Callable<String>() {
        public String call() throws Exception {
            return BeanyPluginCall.this.call(parameters);
        }//from   w  w w  .  ja  v  a2 s .  c o  m
    };
}

From source file:com.googlecode.concurrentlinkedhashmap.MultiThreadedTest.java

@Test(dataProvider = "builder")
public void concurrency(Builder<Integer, Integer> builder) {
    List<Integer> keys = newArrayList();
    Random random = new Random();
    for (int i = 0; i < iterations; i++) {
        keys.add(random.nextInt(iterations / 100));
    }/*from  www . j a  va 2  s  . c  o  m*/
    final List<List<Integer>> sets = shuffle(threads, keys);
    final ConcurrentLinkedHashMap<Integer, Integer> map = builder.maximumWeightedCapacity(capacity())
            .concurrencyLevel(threads).build();
    executeWithTimeOut(map, new Callable<Long>() {
        @Override
        public Long call() throws Exception {
            return timeTasks(threads, new Thrasher(map, sets));
        }
    });
}

From source file:com.linkedin.pinot.common.http.MultiGetRequest.java

/**
 * GET urls in parallel using the executor service.
 * @param urls absolute URLs to GET//  w  w w  . j  a  v a 2  s. co  m
 * @param timeoutMs timeout in milliseconds for each GET request
 * @return instance of CompletionService. Completion service will provide
 *   results as they arrive. The order is NOT same as the order of URLs
 */
public CompletionService<GetMethod> execute(@Nonnull List<String> urls, final int timeoutMs) {
    Preconditions.checkNotNull(urls);
    Preconditions.checkArgument(timeoutMs > 0, "Timeout value for multi-get must be greater than 0");

    CompletionService<GetMethod> completionService = new ExecutorCompletionService<>(executor);
    for (final String url : urls) {
        completionService.submit(new Callable<GetMethod>() {
            @Override
            public GetMethod call() throws Exception {
                HttpClient client = new HttpClient(connectionManager);
                GetMethod getMethod = new GetMethod(url);
                getMethod.getParams().setSoTimeout(timeoutMs);
                // if all connections in the connection manager are busy this will wait to retrieve a connection
                // set time to wait to retrieve a connection from connection manager
                client.getParams().setConnectionManagerTimeout(timeoutMs);
                client.executeMethod(getMethod);
                return getMethod;
            }
        });
    }
    return completionService;
}

From source file:com.microsoft.azure.management.sql.ServiceObjectiveOperationsImpl.java

/**
* Returns information about an Azure SQL Database Server Service Objectives.
*
* @param resourceGroupName Required. The name of the Resource Group to
* which the server belongs./*  w w w. j  a va2  s.  c om*/
* @param serverName Required. The name of the Server.
* @param serviceObjectiveName Required. The name of the service objective
* to retrieve.
* @return Represents the response to a Get Azure Sql Database Service
* Objective request.
*/
@Override
public Future<ServiceObjectiveGetResponse> getAsync(final String resourceGroupName, final String serverName,
        final String serviceObjectiveName) {
    return this.getClient().getExecutorService().submit(new Callable<ServiceObjectiveGetResponse>() {
        @Override
        public ServiceObjectiveGetResponse call() throws Exception {
            return get(resourceGroupName, serverName, serviceObjectiveName);
        }
    });
}

From source file:apiserver.services.images.controllers.info.SizeController.java

/**
 * get basic info about image./*w  w w. ja  va 2s . c  o m*/
 *
 * @param documentId cache id
 * @return height, width, pixel size, transparency
 * , @RequestPart("meta-data") Object metadata
 * <p/>
 * , @RequestParam MultipartFile file
 */
@ApiOperation(value = "Get the height and width for the image", response = Map.class)
@RequestMapping(value = "/info/{documentId}/size", method = { RequestMethod.GET })
public WebAsyncTask<ResponseEntity<Map>> imageInfoByImageAsync(
        @ApiParam(name = "documentId", required = true, defaultValue = "8D981024-A297-4169-8603-E503CC38EEDA") @PathVariable(value = "documentId") String documentId)
        throws ExecutionException, TimeoutException, InterruptedException {
    final String _documentId = documentId;

    Callable<ResponseEntity<Map>> callable = new Callable<ResponseEntity<Map>>() {
        @Override
        public ResponseEntity<Map> call() throws Exception {
            FileInfoJob args = new FileInfoJob();
            args.setDocumentId(_documentId);

            Future<Map> imageFuture = gateway.imageSize(args);
            Map payload = imageFuture.get(defaultTimeout, TimeUnit.MILLISECONDS);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            ResponseEntity<Map> result = new ResponseEntity<Map>(payload, headers, HttpStatus.OK);
            return result;
        }
    };

    return new WebAsyncTask<ResponseEntity<Map>>(defaultTimeout, callable);
}

From source file:edu.cornell.med.icb.R.RUtils.java

/**
 * Can be used to start a rserve instance.
 * @param threadPool The ExecutorService used to start the Rserve process
 * @param rServeCommand Full path to command used to start Rserve process
 * @param host Host where the command should be sent
 * @param port Port number where the command should be sent
 * @param username Username to send to the server if authentication is required
 * @param password Password to send to the server if authentication is required
 * @return The return value from the Rserve instance
 *//*from  w w w .j  a  va2 s  .  c  om*/
static Future<Integer> startup(final ExecutorService threadPool, final String rServeCommand, final String host,
        final int port, final String username, final String password) {
    if (LOG.isInfoEnabled()) {
        LOG.info("Attempting to start Rserve on " + host + ":" + port);
    }

    return threadPool.submit(new Callable<Integer>() {
        public Integer call() throws IOException {
            final List<String> commands = new ArrayList<String>();

            // if the host is not local, use ssh to exec the command
            if (!"localhost".equals(host) && !"127.0.0.1".equals(host)
                    && !InetAddress.getLocalHost().equals(InetAddress.getByName(host))) {
                commands.add("ssh");
                commands.add(host);
            }

            // TODO - this will fail when spaces are in the the path to the executable
            CollectionUtils.addAll(commands, rServeCommand.split(" "));
            commands.add("--RS-port");
            commands.add(Integer.toString(port));

            final String[] command = commands.toArray(new String[commands.size()]);
            LOG.debug(ArrayUtils.toString(commands));

            final ProcessBuilder builder = new ProcessBuilder(command);
            builder.redirectErrorStream(true);
            final Process process = builder.start();
            BufferedReader br = null;
            try {
                final InputStream is = process.getInputStream();
                final InputStreamReader isr = new InputStreamReader(is);
                br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(host + ":" + port + "> " + line);
                    }
                }

                process.waitFor();
                if (LOG.isInfoEnabled()) {
                    LOG.info("Rserve on " + host + ":" + port + " terminated");
                }
            } catch (InterruptedException e) {
                LOG.error("Interrupted!", e);
                process.destroy();
                Thread.currentThread().interrupt();
            } finally {
                IOUtils.closeQuietly(br);
            }

            final int exitValue = process.exitValue();
            if (LOG.isInfoEnabled()) {
                LOG.info("Rserve on " + host + ":" + port + " returned " + exitValue);
            }
            return exitValue;
        }
    });
}

From source file:com.microsoft.windowsazure.management.sql.ServiceObjectiveOperationsImpl.java

/**
* Returns information about a certain Service Objective with a specific Id.
*
* @param serverName Required. The name of the Azure SQL Database Server to
* be queried./* ww  w. j a va  2 s  .co  m*/
* @param serviceObjectiveId Required. The Id of the Service Objective to be
* obtained.
* @return Response containing the service objective for a given Azure SQL
* Database Server with matching service objective Id.
*/
@Override
public Future<ServiceObjectiveGetResponse> getAsync(final String serverName, final String serviceObjectiveId) {
    return this.getClient().getExecutorService().submit(new Callable<ServiceObjectiveGetResponse>() {
        @Override
        public ServiceObjectiveGetResponse call() throws Exception {
            return get(serverName, serviceObjectiveId);
        }
    });
}

From source file:io.druid.metadata.SQLMetadataConnector.java

public <T> T retryWithHandle(final HandleCallback<T> callback) {
    final Callable<T> call = new Callable<T>() {
        @Override/*ww  w .  jav a2s  .  c o m*/
        public T call() throws Exception {
            return getDBI().withHandle(callback);
        }
    };
    final int maxTries = 10;
    try {
        return RetryUtils.retry(call, shouldRetry, maxTries);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}