Example usage for java.util.concurrent CompletionService submit

List of usage examples for java.util.concurrent CompletionService submit

Introduction

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

Prototype

Future<V> submit(Runnable task, V result);

Source Link

Document

Submits a Runnable task for execution and returns a Future representing that task.

Usage

From source file:org.geowebcache.sqlite.MbtilesBlobStore.java

/**
 * Helper method that delete the provided files.
 *///  w w w  .j  av a 2  s. c o m
private boolean deleteFiles(List<File> files) throws StorageException {
    if (files.isEmpty()) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("No files to delete.");
        }
        return false;
    }
    // asking the connection manager to remove the database files
    CompletionService completionService = new ExecutorCompletionService(executorService);
    int tasks = 0;
    for (File file : files) {
        completionService.submit(() -> connectionManager.delete(file), true);
        tasks++;
    }
    // let's wait for the tasks to finish
    for (int i = 0; i < tasks; i++) {
        try {
            completionService.take().get();
        } catch (Exception exception) {
            throw Utils.exception(exception, "Something bad happen when deleting files.");
        }
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Files deleted.");
    }
    return true;
}

From source file:org.geowebcache.sqlite.MbtilesBlobStore.java

@Override
public boolean delete(TileRange tileRange) throws StorageException {
    // getting the files associated with this tile range
    Map<File, List<long[]>> files = fileManager.getFiles(tileRange);
    if (files.isEmpty()) {
        // no files so nothing to do
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Nothing to do.");
        }// w w  w  .j a  v a  2 s  .  co m
        return false;
    }
    // let's delete the tiles
    CompletionService completionService = new ExecutorCompletionService(executorService);
    int tasks = 0;
    for (Map.Entry<File, List<long[]>> entry : files.entrySet()) {
        // FIXME: should we tell something to the listeners ?
        File file = entry.getKey();
        if (!file.exists()) {
            // this database file doesn't exists, so nothing to do
            continue;
        }
        if (eagerDelete) {
            // we delete the whole file avoiding fragmentation on the database
            completionService.submit(() -> connectionManager.delete(file), true);
        } else {
            // we need to delete all tiles that belong to the tiles range and are stored in the current file
            for (long[] range : entry.getValue()) {
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug(String.format(
                            "Deleting tiles range [minx=%d, miny=%d, maxx=%d, maxxy=%d, zoom=%d] in file '%s'.",
                            range[0], range[1], range[2], range[3], range[4], file));
                }
                completionService.submit(() -> connectionManager.executeSql(file,
                        "DELETE FROM tiles WHERE zoom_level = ? AND tile_column BETWEEN ? AND ? AND tile_row BETWEEN ? AND ?;",
                        range[4], range[0], range[2], range[1], range[3]), true);
            }
        }
        tasks++;
    }
    // let's wait for the tasks to finish
    for (int i = 0; i < tasks; i++) {
        try {
            completionService.take().get();
        } catch (Exception exception) {
            throw Utils.exception(exception, "Something bad happen when deleting tile range.");
        }
    }
    return true;
}

From source file:org.apache.nifi.cluster.manager.impl.WebClusterManager.java

/**
 * A helper method to disconnect nodes that returned unsuccessful HTTP responses because of a replicated request. Disconnection requests are sent concurrently.
 *
 *//*from  w w w. j  a v a 2s.  c om*/
private void disconnectNodes(final Set<NodeResponse> nodeResponses, final String explanation) {
    // return fast if nothing to do
    if (nodeResponses == null || nodeResponses.isEmpty()) {
        return;
    }

    final ExecutorService executorService = Executors
            .newFixedThreadPool(properties.getClusterManagerProtocolThreads());
    final CompletionService<Void> completionService = new ExecutorCompletionService<>(executorService);
    for (final NodeResponse nodeResponse : nodeResponses) {
        completionService.submit(new Runnable() {
            @Override
            public void run() {
                final NodeIdentifier nodeId = nodeResponse.getNodeId();
                final int responseStatus = nodeResponse.getStatus();
                final URI requestUri = nodeResponse.getRequestUri();
                final StringBuilder msgBuilder = new StringBuilder();
                msgBuilder.append("Requesting disconnection for node ").append(nodeId)
                        .append(" for request URI ").append(requestUri);
                if (nodeResponse.hasThrowable()) {
                    msgBuilder.append(" because manager encountered exception when issuing request: ")
                            .append(nodeResponse.getThrowable());
                    // log stack trace anytime we have a throwable
                    ((NiFiLog) logger).getWrappedLog().info(msgBuilder.toString(), nodeResponse.getThrowable());
                    addEvent(nodeId,
                            "Manager encountered exception when issuing request for URI " + requestUri);
                    addBulletin(nodeId, Severity.ERROR,
                            "Manager encountered exception when issuing request for URI " + requestUri
                                    + "; node will be disconnected");
                } else {
                    msgBuilder.append(" because HTTP response status was ").append(responseStatus);
                    logger.info(msgBuilder.toString());
                    addEvent(nodeId, "HTTP response status was unsuccessful (" + responseStatus
                            + ") for request URI " + requestUri);
                    addBulletin(nodeId, Severity.ERROR, "HTTP response status was unsuccessful ("
                            + responseStatus + ") for request URI " + requestUri);
                }
                requestDisconnectionQuietly(nodeId, explanation);
            }
        }, null);
    }

    executorService.shutdown();
}

From source file:org.apache.nifi.cluster.manager.impl.WebClusterManager.java

/**
 * Drains the node responses off of the socket to ensure that the socket is appropriately cleaned-up.
 *
 * @param nodeResponses the collection of node responses
 *//*w  w  w  .  ja  v  a 2s.  com*/
private void drainResponses(final Collection<NodeResponse> nodeResponses) {
    // fail fast if nothing to do
    if (nodeResponses.isEmpty()) {
        return;
    }

    final ExecutorService executorService = Executors
            .newFixedThreadPool(properties.getClusterManagerProtocolThreads());
    final CompletionService<Void> completionService = new ExecutorCompletionService<>(executorService);
    for (final NodeResponse nodeResponse : nodeResponses) {
        // if we received a response, then clear out the response data
        if (!nodeResponse.hasThrowable()) {
            completionService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        try (final OutputStream drain = new OutputStream() {
                            @Override
                            public void write(final int b) {
                                /* drain response */ }
                        }) {
                            ((StreamingOutput) nodeResponse.getResponse().getEntity()).write(drain);
                        }
                    } catch (final IOException | WebApplicationException ex) {
                        logger.info("Failed clearing out non-client response buffer due to: " + ex, ex);
                    }
                }
            }, null);
        }
    }

    executorService.shutdown();
}