Search in sources :

Example 1 with Collectors.toList

use of java8.util.stream.Collectors.toList in project streamsupport by stefan-zobel.

the class CompletableFutureTest method testMinimalCompletionStage_minimality.

/**
 * Minimal completion stages throw UOE for most non-CompletionStage methods
 */
public void testMinimalCompletionStage_minimality() {
    if (!testImplementationDetails)
        return;
    Function<Method, String> toSignature = method -> method.getName() + Arrays.toString(method.getParameterTypes());
    Predicate<Method> isNotStatic = method -> (method.getModifiers() & Modifier.STATIC) == 0;
    List<Method> minimalMethods = RefStreams.of(Object.class, CompletionStage.class).flatMap(klazz -> RefStreams.of(klazz.getMethods())).filter(isNotStatic).collect(Collectors.toList());
    // Methods from CompletableFuture permitted NOT to throw UOE
    String[] signatureWhitelist = { "newIncompleteFuture[]", "defaultExecutor[]", "minimalCompletionStage[]", "copy[]" };
    Set<String> permittedMethodSignatures = RefStreams.concat(StreamSupport.stream(minimalMethods).map(toSignature), RefStreams.of(signatureWhitelist)).collect(Collectors.toSet());
    List<Method> allMethods = RefStreams.of(CompletableFuture.class.getMethods()).filter(isNotStatic).filter(method -> !permittedMethodSignatures.contains(toSignature.apply(method))).collect(Collectors.toList());
    List<CompletionStage<Integer>> stages = new ArrayList<CompletionStage<Integer>>();
    CompletionStage<Integer> min = new CompletableFuture<Integer>().minimalCompletionStage();
    stages.add(min);
    stages.add(min.thenApply(x -> x));
    stages.add(CompletableFuture.completedStage(1));
    stages.add(CompletableFuture.failedStage(new CFException()));
    List<Method> bugs = new ArrayList<>();
    for (Method method : allMethods) {
        Class<?>[] parameterTypes = method.getParameterTypes();
        Object[] args = new Object[parameterTypes.length];
        // Manufacture boxed primitives for primitive params
        for (int i = 0; i < args.length; i++) {
            Class<?> type = parameterTypes[i];
            if (type == boolean.class)
                args[i] = false;
            else if (type == int.class)
                args[i] = 0;
            else if (type == long.class)
                args[i] = 0L;
        }
        for (CompletionStage<Integer> stage : stages) {
            try {
                method.invoke(stage, args);
                bugs.add(method);
            } catch (java.lang.reflect.InvocationTargetException expected) {
                if (!(expected.getCause() instanceof UnsupportedOperationException)) {
                    bugs.add(method);
                // expected.getCause().printStackTrace();
                }
            } catch (Exception bad) {
                throw new Error(bad);
            }
        }
    }
    if (!bugs.isEmpty())
        throw new Error("Methods did not throw UOE: " + bugs);
}
Also used : Arrays(java.util.Arrays) Test(junit.framework.Test) TimeoutException(java.util.concurrent.TimeoutException) Callable(java.util.concurrent.Callable) CompletableFuture.completedFuture(java8.util.concurrent.CompletableFuture.completedFuture) Predicate(java8.util.function.Predicate) AtomicReference(java.util.concurrent.atomic.AtomicReference) CompletableFuture.failedFuture(java8.util.concurrent.CompletableFuture.failedFuture) Function(java8.util.function.Function) ArrayList(java.util.ArrayList) TestSuite(junit.framework.TestSuite) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) BiFunction(java8.util.function.BiFunction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Consumer(java8.util.function.Consumer) ForkJoinPool(java8.util.concurrent.ForkJoinPool) Method(java.lang.reflect.Method) CompletionStage(java8.util.concurrent.CompletionStage) Objects(java8.util.Objects) CancellationException(java.util.concurrent.CancellationException) Executor(java.util.concurrent.Executor) ForkJoinTask(java8.util.concurrent.ForkJoinTask) Set(java.util.Set) Collectors(java8.util.stream.Collectors) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) StreamSupport(java8.util.stream.StreamSupport) Supplier(java8.util.function.Supplier) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) CompletableFuture(java8.util.concurrent.CompletableFuture) BiConsumer(java8.util.function.BiConsumer) RefStreams(java8.util.stream.RefStreams) Modifier(java.lang.reflect.Modifier) CompletionException(java8.util.concurrent.CompletionException) SECONDS(java.util.concurrent.TimeUnit.SECONDS) ArrayList(java.util.ArrayList) CompletionStage(java8.util.concurrent.CompletionStage) Method(java.lang.reflect.Method) TimeoutException(java.util.concurrent.TimeoutException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) CancellationException(java.util.concurrent.CancellationException) ExecutionException(java.util.concurrent.ExecutionException) CompletionException(java8.util.concurrent.CompletionException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 2 with Collectors.toList

use of java8.util.stream.Collectors.toList in project streamsupport by stefan-zobel.

the class Collection8Test method testDetectRaces.

/**
 * Motley crew of threads concurrently randomly hammer the collection.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test(dataProvider = "Source")
public void testDetectRaces(String description, Supplier<CollectionImplementation> sci) throws Throwable {
    CollectionImplementation impl = sci.get();
    if (!impl.isConcurrent())
        return;
    if (HAS_JAVA8_SPLITERATOR_BUG && LinkedBlockingDeque.class.equals(impl.klazz())) {
        // https://bugs.openjdk.java.net/browse/JDK-8169739
        return;
    }
    if (CopyOnWriteArraySet.class.equals(impl.klazz())) {
        return;
    }
    final ThreadLocalRandom rnd = ThreadLocalRandom.current();
    final Collection c = impl.emptyCollection();
    final long testDurationMillis = expensiveTests ? LONG_DELAY_MS : timeoutMillis();
    final AtomicBoolean done = new AtomicBoolean(false);
    final Object one = impl.makeElement(1);
    final Object two = impl.makeElement(2);
    final Consumer checkSanity = x -> assertTrue(x == one || x == two);
    final Consumer<Object[]> checkArraySanity = array -> {
        // assertTrue(array.length <= 2); // duplicates are permitted
        for (Object x : array) assertTrue(x == one || x == two);
    };
    final Object[] emptyArray = (Object[]) java.lang.reflect.Array.newInstance(one.getClass(), 0);
    final List<Future<?>> futures;
    // register this thread
    final Phaser threadsStarted = new Phaser(1);
    final Runnable[] frobbers = { () -> Iterables.forEach(c, checkSanity), () -> StreamSupport.stream(c).forEach(checkSanity), () -> StreamSupport.parallelStream(c).forEach(checkSanity), () -> Spliterators.spliterator(c).trySplit(), () -> {
        Spliterator<?> s = Spliterators.spliterator(c);
        s.tryAdvance(checkSanity);
        s.trySplit();
    }, () -> {
        Spliterator<?> s = Spliterators.spliterator(c);
        do {
        } while (s.tryAdvance(checkSanity));
    }, () -> {
        for (Object x : c) checkSanity.accept(x);
    }, () -> checkArraySanity.accept(c.toArray()), () -> checkArraySanity.accept(c.toArray(emptyArray)), () -> {
        Object[] a = new Object[5];
        Object three = impl.makeElement(3);
        Arrays.fill(a, 0, a.length, three);
        Object[] x = c.toArray(a);
        if (x == a)
            for (int i = 0; i < a.length && a[i] != null; i++) checkSanity.accept(a[i]);
        else
            // A careful reading of the spec does not support:
            // for (i++; i < a.length; i++) assertSame(three, a[i]);
            checkArraySanity.accept(x);
    }, adderRemover(c, one), adderRemover(c, two) };
    final List<Runnable> tasks = J8Arrays.stream(frobbers).filter(// random subset
    task -> rnd.nextBoolean()).map(task -> (Runnable) () -> {
        threadsStarted.arriveAndAwaitAdvance();
        while (!done.get()) task.run();
    }).collect(Collectors.<Runnable>toList());
    final ExecutorService pool = Executors.newCachedThreadPool();
    PoolCleaner cleaner = null;
    try {
        cleaner = cleaner(pool, done);
        threadsStarted.bulkRegister(tasks.size());
        futures = StreamSupport.stream(tasks).map(pool::submit).collect(Collectors.toList());
        threadsStarted.arriveAndDeregister();
        Thread.sleep(testDurationMillis);
    } finally {
        if (cleaner != null) {
            cleaner.close();
        }
    }
    for (Future<?> future : futures) assertNull(future.get(0L, MILLISECONDS));
}
Also used : Arrays(java.util.Arrays) DataProvider(org.testng.annotations.DataProvider) PriorityQueue(java.util.PriorityQueue) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.testng.annotations.Test) Iterables(java8.lang.Iterables) Deque(java.util.Deque) Predicate(java8.util.function.Predicate) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) PriorityBlockingQueue(java.util.concurrent.PriorityBlockingQueue) HashSet(java.util.HashSet) Phaser(java8.util.concurrent.Phaser) Iterators(java8.util.Iterators) Future(java.util.concurrent.Future) J8Arrays(java8.util.J8Arrays) Vector(java.util.Vector) Consumer(java8.util.function.Consumer) LinkedList(java.util.LinkedList) NoSuchElementException(java.util.NoSuchElementException) ExecutorService(java.util.concurrent.ExecutorService) Iterator(java.util.Iterator) BlockingDeque(java.util.concurrent.BlockingDeque) Collection(java.util.Collection) Spliterator(java8.util.Spliterator) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) Collectors(java8.util.stream.Collectors) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Spliterators(java8.util.Spliterators) CopyOnWriteArraySet(java.util.concurrent.CopyOnWriteArraySet) StreamSupport(java8.util.stream.StreamSupport) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Executors(java.util.concurrent.Executors) Supplier(java8.util.function.Supplier) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) ThreadLocalRandom(java8.util.concurrent.ThreadLocalRandom) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) HOURS(java.util.concurrent.TimeUnit.HOURS) Queue(java.util.Queue) ArrayDeque(java.util.ArrayDeque) Collections(java.util.Collections) ConcurrentModificationException(java.util.ConcurrentModificationException) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Consumer(java8.util.function.Consumer) ExecutorService(java.util.concurrent.ExecutorService) ThreadLocalRandom(java8.util.concurrent.ThreadLocalRandom) Collection(java.util.Collection) Future(java.util.concurrent.Future) Phaser(java8.util.concurrent.Phaser) Test(org.testng.annotations.Test)

Aggregations

ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 List (java.util.List)2 Set (java.util.Set)2 MILLISECONDS (java.util.concurrent.TimeUnit.MILLISECONDS)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Method (java.lang.reflect.Method)1 Modifier (java.lang.reflect.Modifier)1 ArrayDeque (java.util.ArrayDeque)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 ConcurrentModificationException (java.util.ConcurrentModificationException)1 Deque (java.util.Deque)1 HashSet (java.util.HashSet)1 Iterator (java.util.Iterator)1 LinkedList (java.util.LinkedList)1 NoSuchElementException (java.util.NoSuchElementException)1 PriorityQueue (java.util.PriorityQueue)1 Queue (java.util.Queue)1 Vector (java.util.Vector)1