Example usage for java.util.concurrent CompletableFuture supplyAsync

List of usage examples for java.util.concurrent CompletableFuture supplyAsync

Introduction

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

Prototype

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor) 

Source Link

Document

Returns a new CompletableFuture that is asynchronously completed by a task running in the given executor with the value obtained by calling the given Supplier.

Usage

From source file:org.jboss.set.aphrodite.issue.trackers.jira.JiraIssueTracker.java

@Override
public boolean addCommentToIssue(Map<Issue, Comment> commentMap) {
    commentMap = filterIssuesByHost(commentMap);
    List<CompletableFuture<Boolean>> requests = commentMap.entrySet().stream()
            .map(entry -> CompletableFuture.supplyAsync(
                    () -> postCommentAndLogExceptions(entry.getKey(), entry.getValue()), executorService))
            .collect(Collectors.toList());

    return requests.stream().map(CompletableFuture::join).noneMatch(failed -> !failed);
}

From source file:org.jboss.set.aphrodite.issue.trackers.jira.JiraIssueTracker.java

@Override
public boolean addCommentToIssue(Collection<Issue> issues, Comment comment) {
    issues = filterIssuesByHost(issues);

    List<CompletableFuture<Boolean>> requests = issues
            .stream().map(issue -> CompletableFuture
                    .supplyAsync(() -> postCommentAndLogExceptions(issue, comment), executorService))
            .collect(Collectors.toList());

    return requests.stream().map(CompletableFuture::join).noneMatch(failed -> !failed);
}

From source file:org.nuxeo.ecm.core.TestSQLRepositoryQuery.java

@Test
public void testScrollApiConcurrency() throws Exception {
    final int nbDocs = 127;
    final int batchSize = 13;
    final int nbThread = nbDocs / batchSize + 1;
    // System.out.println("nbDocs: " + nbDocs + ", batch: " + batchSize + ", thread: " + nbThread);
    DocumentModel doc;// www  .  jav  a2  s  .c om
    for (int i = 0; i < nbDocs; i++) {
        doc = new DocumentModelImpl("/", "doc1", "File");
        session.createDocument(doc);
    }
    session.save();

    DocumentModelList dml;
    dml = session.query("SELECT * FROM Document");
    assertEquals(nbDocs, dml.size());

    ScrollResult ret = session.scroll("SELECT * FROM Document", batchSize, 10);
    List<String> ids = ret.getResultIds();
    int total = ids.size();
    String scrollId = ret.getScrollId();
    // System.out.println("first call: " + total);
    List<CompletableFuture<Integer>> futures = new ArrayList<>(nbThread);
    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(nbThread);
    final CountDownLatch latch = new CountDownLatch(nbThread);
    for (int n = 0; n < nbThread; n++) {
        CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> {
            TransactionHelper.startTransaction();
            try {
                // make sure all threads ask to scroll at the same time
                latch.countDown();
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    ExceptionUtils.checkInterrupt(e);
                }
                int nb = session.scroll(scrollId).getResultIds().size();
                // System.out.println(Thread.currentThread().getName() + ": return: " + nb);
                return nb;
            } finally {
                TransactionHelper.commitOrRollbackTransaction();
            }
        }, executor);
        futures.add(completableFuture);
    }
    for (int n = 0; n < nbThread; n++) {
        int count = futures.get(n).get();
        total += count;
    }
    assertEquals(nbDocs, total);
}

From source file:org.nuxeo.ecm.core.TestSQLRepositoryQuery.java

@Test
public void testScrollCleaningConcurrency() throws Exception {
    final int NB_TRHEADS = 15;
    final int NB_SCROLLS = 100;

    assumeTrue("Backend must support true scrolling", supportsScroll());

    DocumentModel doc = new DocumentModelImpl("/", "doc1", "File");
    session.createDocument(doc);//from  w w w .j  a  va  2 s  .  c  o  m
    doc = new DocumentModelImpl("/", "doc2", "File");
    session.createDocument(doc);
    session.save();
    ScrollResult ret;
    for (int i = 0; i < NB_SCROLLS; i++) {
        session.scroll("SELECT * FROM Document", 1, 1).getScrollId();
    }
    // wait for timeout
    Thread.sleep(1100);

    List<CompletableFuture<Integer>> futures = new ArrayList<>(NB_TRHEADS);
    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(NB_TRHEADS);
    final CountDownLatch latch = new CountDownLatch(NB_TRHEADS);
    for (int n = 0; n < NB_TRHEADS; n++) {

        CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> {
            TransactionHelper.startTransaction();
            try {
                // make sure all threads ask to scroll at the same time
                latch.countDown();
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    ExceptionUtils.checkInterrupt(e);
                }
                session.scroll("SELECT * FROM Document", 1, 1).getResultIds().size();
                return 1;
            } finally {
                TransactionHelper.commitOrRollbackTransaction();
            }
        }, executor);
        futures.add(completableFuture);
    }
    int total = 0;
    for (int n = 0; n < NB_TRHEADS; n++) {
        int count = futures.get(n).get();
        total += count;
    }
    assertEquals(NB_TRHEADS, total);
}

From source file:org.onosproject.p4runtime.ctl.P4RuntimeClientImpl.java

/**
 * Executes the given task (supplier) in the gRPC context executor of this client, such that if the context is
 * cancelled (e.g. client shutdown) the RPC is automatically cancelled.
 * <p>//www  .  j  av  a  2s.co  m
 * Important: Tasks submitted in parallel by different threads are forced executed sequentially.
 * <p>
 */
private <U> CompletableFuture<U> supplyInContext(Supplier<U> supplier, String opDescription) {
    return CompletableFuture.supplyAsync(() -> {
        // TODO: explore a more relaxed locking strategy.
        writeLock.lock();
        try {
            return supplier.get();
        } catch (StatusRuntimeException ex) {
            log.warn("Unable to execute {} on {}: {}", opDescription, deviceId, ex.toString());
            throw ex;
        } catch (Throwable ex) {
            log.error("Exception in client of {}, executing {}", deviceId, opDescription, ex);
            throw ex;
        } finally {
            writeLock.unlock();
        }
    }, contextExecutor);
}

From source file:org.onosproject.store.primitives.impl.CopycatTransportClient.java

@Override
public CompletableFuture<Connection> connect(Address remoteAddress) {
    ThreadContext context = ThreadContext.currentContextOrThrow();
    CopycatTransportConnection connection = new CopycatTransportConnection(nextConnectionId(),
            CopycatTransport.Mode.CLIENT, partitionId, remoteAddress, messagingService, context);
    if (mode == CopycatTransport.Mode.CLIENT) {
        connection.setBidirectional();//from www . java 2 s .  co  m
    }
    connections.add(connection);
    return CompletableFuture.supplyAsync(() -> connection, context.executor());
}

From source file:org.onosproject.store.primitives.impl.CopycatTransportServer.java

private void listen(Address address, Consumer<Connection> listener, ThreadContext context) {
    messagingService.registerHandler(messageSubject, (sender, payload) -> {
        try (DataInputStream input = new DataInputStream(new ByteArrayInputStream(payload))) {
            long connectionId = input.readLong();
            AtomicBoolean newConnectionCreated = new AtomicBoolean(false);
            CopycatTransportConnection connection = connections.computeIfAbsent(connectionId, k -> {
                newConnectionCreated.set(true);
                CopycatTransportConnection newConnection = new CopycatTransportConnection(connectionId,
                        CopycatTransport.Mode.SERVER, partitionId, CopycatTransport.toAddress(sender),
                        messagingService, getOrCreateContext(context));
                log.debug("Created new incoming connection {}", connectionId);
                newConnection.closeListener(c -> connections.remove(connectionId, c));
                return newConnection;
            });//  www.ja  v  a2 s.  c  o  m
            byte[] request = IOUtils.toByteArray(input);
            return CompletableFuture.supplyAsync(() -> {
                if (newConnectionCreated.get()) {
                    listener.accept(connection);
                }
                return connection;
            }, context.executor()).thenCompose(c -> c.handle(request));
        } catch (IOException e) {
            return Tools.exceptionalFuture(e);
        }
    });
    context.execute(() -> {
        listenFuture.complete(null);
    });
}

From source file:org.polymap.p4.catalog.AllResolver.java

protected CompletableFuture<IResolvableInfo> doResolve(IMetadata metadata, IProgressMonitor monitor) {
    for (IMetadataResourceResolver resolver : resolvers) {
        if (resolver.canResolve(metadata)) {
            return CompletableFuture.supplyAsync(() -> {
                try {
                    IProgressMonitor mon = monitor != null ? monitor : UIJob.monitorOfThread();
                    return resolver.resolve(metadata, mon);
                } catch (Exception e) {
                    log.warn("", e);
                    throw Throwables.propagate(e);
                }/* ww w .j a v a2s.c  o  m*/
            }, JobExecutor.instance());
        }
    }
    throw new IllegalStateException("Unable to resolve: " + metadata);
}

From source file:org.polymap.p4.layer.FeatureLayer.java

/**
 * Waits for the {@link FeatureLayer} of the given {@link ILayer}.
 * <p/>/*from  w w  w . j a  v a  2  s  .  c  om*/
 * Avoid calling just {@link CompletableFuture#get()} as this may block the
 * calling (UI) thread. Instead register callbacks that handle the result
 * asynchronously.
 * <p/>
 * The callbacks are called from within an {@link UIJob}. Use
 * {@link UIThreadExecutor} to do somethinf in the display thread.
 * <p/>
 * <b>Example usage:</b>
 * <pre>
 *      FeatureLayer.of( layer ).thenAccept( featureLayer -> {
 *          if (featureLayer.isPresent()) {
 *              ...
 *          }
 *          else {
 *              ...
 *          }
 *      })
 *      .exceptionally( e -> {
 *          StatusDispatcher.handleError( "", e );
 *          return null;
 *      });
 * </pre>
 * 
 * @param layer
 */
public static CompletableFuture<Optional<FeatureLayer>> of(ILayer layer) {
    return CompletableFuture.supplyAsync(() -> {
        SessionHolder session = SessionHolder.instance(SessionHolder.class);
        FeatureLayer result = session.instances.computeIfAbsent((String) layer.id(), key -> {
            try {
                IProgressMonitor monitor = UIJob.monitorOfThread();
                return new FeatureLayer(layer).doConnectLayer(monitor);
            } catch (Exception e) {
                throw new CompletionException(e);
            }
        });
        return result.isValid() ? Optional.of(result) : Optional.empty();
    }, JobExecutor.instance());
}

From source file:org.polymap.p4.layer.RasterLayer.java

/**
 * Waits for the {@link RasterLayer} of the given {@link ILayer}.
 * <p/>//from  w  ww . j ava  2 s . c  om
 * Avoid calling just {@link CompletableFuture#get()} as this may block the
 * calling (UI) thread. Instead register callbacks that handle the result
 * asynchronously.
 * <p/>
 * The callbacks are called from within an {@link UIJob}. Use
 * {@link UIThreadExecutor} to do somethinf in the display thread.
 * <p/>
 * <b>Example usage:</b>
 * <pre>
 *      RasterLayer.of( layer ).thenAccept( rl -> {
 *          if (rl.isPresent()) {
 *              ...
 *          }
 *          else {
 *              ...
 *          }
 *      })
 *      .exceptionally( e -> {
 *          StatusDispatcher.handleError( "", e );
 *          return null;
 *      });
 * </pre>
 * 
 * @param layer
 */
public static CompletableFuture<Optional<RasterLayer>> of(ILayer layer) {
    return CompletableFuture.supplyAsync(() -> {
        SessionHolder session = SessionHolder.instance(SessionHolder.class);
        RasterLayer result = session.instances.computeIfAbsent((String) layer.id(), key -> {
            try {
                IProgressMonitor monitor = UIJob.monitorOfThread();
                return new RasterLayer(layer).doConnectLayer(monitor);
            } catch (Exception e) {
                throw new CompletionException(e);
            }
        });
        return result.isValid() ? Optional.of(result) : Optional.empty();
    }, JobExecutor.instance());
}