Java AtomicInteger waitForAll(List> futures)

Here you can find the source of waitForAll(List> futures)

Description

Return a future that represents the completion of the futures in the provided list

License

Apache License

Parameter

Parameter Description
futures a parameter

Declaration

public static <T> CompletableFuture<T> waitForAll(List<CompletableFuture<T>> futures) 

Method Source Code

//package com.java2s;
/**//  w ww. ja  v  a 2 s  .  c o  m
 * Copyright 2016 Yahoo Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class Main {
    /**
     * Return a future that represents the completion of the futures in the provided list
     *
     * @param futures
     * @return
     */
    public static <T> CompletableFuture<T> waitForAll(List<CompletableFuture<T>> futures) {
        if (futures.isEmpty()) {
            return CompletableFuture.completedFuture(null);
        }

        final CompletableFuture<T> compositeFuture = new CompletableFuture<>();
        final AtomicInteger count = new AtomicInteger(futures.size());
        final AtomicReference<Throwable> exception = new AtomicReference<>();

        for (CompletableFuture<T> future : futures) {
            future.whenComplete((r, ex) -> {
                if (ex != null) {
                    exception.compareAndSet(null, ex);
                }
                if (count.decrementAndGet() == 0) {
                    // All the pending futures did complete
                    if (exception.get() != null) {
                        compositeFuture.completeExceptionally(exception.get());
                    } else {
                        compositeFuture.complete(null);
                    }
                }
            });
        }

        return compositeFuture;
    }
}

Related

  1. setBitIfUnsetByIndex(final AtomicInteger ai, final int n)
  2. storeStoreBarrier()
  3. timeToId(long timeInMillis)
  4. tokenize(String string)
  5. uniqueSequenceId()
  6. waitForEvents(long sleepTime, AtomicBoolean condition, long timeout)
  7. waitForEvents(long sleepTime, int expectedCount, AtomicInteger actualCount, long timeout)
  8. waitForEvents(long sleepTime, int expectedCount, AtomicInteger actualCount, long timeout)