Search in sources :

Example 1 with ThreadLocalRandom

use of java8.util.concurrent.ThreadLocalRandom in project streamsupport by stefan-zobel.

the class Collection8Test method testElementRemovalDuringTraversal.

/**
 * All elements removed in the middle of CONCURRENT traversal.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test(dataProvider = "Source")
public void testElementRemovalDuringTraversal(String description, Supplier<CollectionImplementation> sci) {
    CollectionImplementation impl = sci.get();
    if (HAS_JAVA8_SPLITERATOR_BUG && LinkedBlockingQueue.class.equals(impl.klazz())) {
        // https://bugs.openjdk.java.net/browse/JDK-8171051
        return;
    }
    Collection<Object> c = impl.emptyCollection();
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    int n = rnd.nextInt(6);
    ArrayList copy = new ArrayList();
    for (int i = 0; i < n; i++) {
        Object x = impl.makeElement(i);
        copy.add(x);
        c.add(x);
    }
    ArrayList iterated = new ArrayList();
    ArrayList spliterated = new ArrayList();
    Spliterator<?> s = Spliterators.spliterator(c);
    Iterator<?> it = c.iterator();
    for (int i = rnd.nextInt(n + 1); --i >= 0; ) {
        assertTrue(s.tryAdvance(spliterated::add));
        if (rnd.nextBoolean())
            assertTrue(it.hasNext());
        iterated.add(it.next());
    }
    Consumer alwaysThrows = e -> {
        throw new AssertionError();
    };
    if (s.hasCharacteristics(Spliterator.CONCURRENT)) {
        // TODO: many more removal methods
        c.clear();
        if (testImplementationDetails && !(c instanceof java.util.concurrent.ArrayBlockingQueue)) {
            if (rnd.nextBoolean())
                assertFalse(s.tryAdvance(alwaysThrows));
            else
                s.forEachRemaining(alwaysThrows);
        }
        if (it.hasNext())
            iterated.add(it.next());
        if (rnd.nextBoolean())
            assertIteratorExhausted(it);
    }
    assertTrue(copy.containsAll(iterated));
    assertTrue(copy.containsAll(spliterated));
}
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) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Consumer(java8.util.function.Consumer) ThreadLocalRandom(java8.util.concurrent.ThreadLocalRandom) Test(org.testng.annotations.Test)

Example 2 with ThreadLocalRandom

use of java8.util.concurrent.ThreadLocalRandom in project streamsupport by stefan-zobel.

the class Collection8Test method testTraversalEquivalence.

/**
 * Various ways of traversing a collection yield same elements
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test(dataProvider = "Source")
public void testTraversalEquivalence(String description, Supplier<CollectionImplementation> sci) {
    CollectionImplementation impl = sci.get();
    Collection c = impl.emptyCollection();
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    int n = rnd.nextInt(6);
    for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
    ArrayList iterated = new ArrayList();
    ArrayList iteratedForEachRemaining = new ArrayList();
    ArrayList tryAdvanced = new ArrayList();
    ArrayList spliterated = new ArrayList();
    ArrayList splitonced = new ArrayList();
    ArrayList forEached = new ArrayList();
    ArrayList streamForEached = new ArrayList();
    ConcurrentLinkedQueue parallelStreamForEached = new ConcurrentLinkedQueue();
    ArrayList removeIfed = new ArrayList();
    for (Object x : c) iterated.add(x);
    Iterators.forEachRemaining(c.iterator(), iteratedForEachRemaining::add);
    for (Spliterator s = Spliterators.spliterator(c); s.tryAdvance(tryAdvanced::add); ) {
    }
    Spliterators.spliterator(c).forEachRemaining(spliterated::add);
    {
        // trySplit returns "strict prefix"
        Spliterator<?> s1 = Spliterators.spliterator(c), s2 = s1.trySplit();
        if (s2 != null)
            s2.forEachRemaining(splitonced::add);
        s1.forEachRemaining(splitonced::add);
    }
    Iterables.forEach(c, forEached::add);
    StreamSupport.stream(c).forEach(streamForEached::add);
    StreamSupport.parallelStream(c).forEach(parallelStreamForEached::add);
    Iterables.removeIf(c, e -> {
        removeIfed.add(e);
        return false;
    });
    boolean ordered = Spliterators.spliterator(c).hasCharacteristics(Spliterator.ORDERED);
    if (c instanceof List || c instanceof Deque)
        assertTrue(ordered);
    HashSet<?> cset = new HashSet<>(c);
    assertEquals(cset, new HashSet<>(parallelStreamForEached));
    if (ordered) {
        assertEquals(iterated, iteratedForEachRemaining);
        assertEquals(iterated, tryAdvanced);
        assertEquals(iterated, spliterated);
        assertEquals(iterated, splitonced);
        assertEquals(iterated, forEached);
        assertEquals(iterated, streamForEached);
        assertEquals(iterated, removeIfed);
    } else {
        assertEquals(cset, new HashSet<>(iterated));
        assertEquals(cset, new HashSet<>(iteratedForEachRemaining));
        assertEquals(cset, new HashSet<>(tryAdvanced));
        assertEquals(cset, new HashSet<>(spliterated));
        assertEquals(cset, new HashSet<>(splitonced));
        assertEquals(cset, new HashSet<>(forEached));
        assertEquals(cset, new HashSet<>(streamForEached));
        assertEquals(cset, new HashSet<>(removeIfed));
    }
    if (c instanceof Deque) {
        Deque<?> d = (Deque<?>) c;
        ArrayList descending = new ArrayList();
        ArrayList descendingForEachRemaining = new ArrayList();
        for (Iterator<?> it = d.descendingIterator(); it.hasNext(); ) descending.add(it.next());
        Iterators.forEachRemaining(d.descendingIterator(), e -> descendingForEachRemaining.add(e));
        Collections.reverse(descending);
        Collections.reverse(descendingForEachRemaining);
        assertEquals(iterated, descending);
        assertEquals(iterated, descendingForEachRemaining);
    }
}
Also used : ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Deque(java.util.Deque) BlockingDeque(java.util.concurrent.BlockingDeque) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) ArrayDeque(java.util.ArrayDeque) Collection(java.util.Collection) ThreadLocalRandom(java8.util.concurrent.ThreadLocalRandom) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) Spliterator(java8.util.Spliterator) HashSet(java.util.HashSet) Test(org.testng.annotations.Test)

Example 3 with ThreadLocalRandom

use of java8.util.concurrent.ThreadLocalRandom in project streamsupport by stefan-zobel.

the class Collection8Test method testStickySpliteratorExhaustion.

/**
 * Concurrent Spliterators, once exhausted, stay exhausted.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test(dataProvider = "Source")
public void testStickySpliteratorExhaustion(String description, Supplier<CollectionImplementation> sci) throws Throwable {
    CollectionImplementation impl = sci.get();
    if (HAS_JAVA8_SPLITERATOR_BUG && PriorityBlockingQueue.class.equals(impl.klazz())) {
        // https://bugs.openjdk.java.net/browse/JDK-8172023
        return;
    }
    if (!impl.isConcurrent())
        return;
    if (!testImplementationDetails)
        return;
    final ThreadLocalRandom rnd = ThreadLocalRandom.current();
    final Consumer<?> alwaysThrows = e -> {
        throw new AssertionError();
    };
    final Collection c = impl.emptyCollection();
    final Spliterator s = Spliterators.spliterator(c);
    if (rnd.nextBoolean()) {
        assertFalse(s.tryAdvance(alwaysThrows));
    } else {
        s.forEachRemaining(alwaysThrows);
    }
    final Object one = impl.makeElement(1);
    // Spliterator should not notice added element
    c.add(one);
    if (rnd.nextBoolean()) {
        assertFalse(s.tryAdvance(alwaysThrows));
    } else {
        s.forEachRemaining(alwaysThrows);
    }
}
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) ThreadLocalRandom(java8.util.concurrent.ThreadLocalRandom) Collection(java.util.Collection) PriorityBlockingQueue(java.util.concurrent.PriorityBlockingQueue) Spliterator(java8.util.Spliterator) Test(org.testng.annotations.Test)

Example 4 with ThreadLocalRandom

use of java8.util.concurrent.ThreadLocalRandom in project streamsupport by stefan-zobel.

the class Collection8Test method testRemoveAfterForEachRemaining.

/**
 * Calling Iterator#remove() after Iterator#forEachRemaining
 * should (maybe) remove last element
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test(dataProvider = "Source")
public void testRemoveAfterForEachRemaining(String description, Supplier<CollectionImplementation> sci) {
    CollectionImplementation impl = sci.get();
    Collection c = impl.emptyCollection();
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    testCollection: {
        int n = 3 + rnd.nextInt(2);
        for (int i = 0; i < n; i++) c.add(impl.makeElement(i));
        Iterator<?> it = c.iterator();
        assertTrue(it.hasNext());
        assertEquals(impl.makeElement(0), it.next());
        assertTrue(it.hasNext());
        assertEquals(impl.makeElement(1), it.next());
        Iterators.forEachRemaining(it, e -> assertTrue(c.contains(e)));
        if (testImplementationDetails) {
            if (c instanceof java.util.concurrent.ArrayBlockingQueue) {
                assertIteratorExhausted(it);
            } else {
                try {
                    it.remove();
                } catch (UnsupportedOperationException ok) {
                    break testCollection;
                }
                assertEquals(n - 1, c.size());
                for (int i = 0; i < n - 1; i++) assertTrue(c.contains(impl.makeElement(i)));
                assertFalse(c.contains(impl.makeElement(n - 1)));
            }
        }
    }
    if (c instanceof Deque) {
        Deque d = (Deque) impl.emptyCollection();
        int n = 3 + rnd.nextInt(2);
        for (int i = 0; i < n; i++) d.add(impl.makeElement(i));
        Iterator<?> it = d.descendingIterator();
        assertTrue(it.hasNext());
        assertEquals(impl.makeElement(n - 1), it.next());
        assertTrue(it.hasNext());
        assertEquals(impl.makeElement(n - 2), it.next());
        Iterators.forEachRemaining(it, e -> assertTrue(c.contains(e)));
        if (testImplementationDetails) {
            it.remove();
            assertEquals(n - 1, d.size());
            for (int i = 1; i < n; i++) assertTrue(d.contains(impl.makeElement(i)));
            assertFalse(d.contains(impl.makeElement(0)));
        }
    }
}
Also used : Collection(java.util.Collection) ThreadLocalRandom(java8.util.concurrent.ThreadLocalRandom) Deque(java.util.Deque) BlockingDeque(java.util.concurrent.BlockingDeque) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) ArrayDeque(java.util.ArrayDeque) Test(org.testng.annotations.Test)

Example 5 with ThreadLocalRandom

use of java8.util.concurrent.ThreadLocalRandom in project streamsupport by stefan-zobel.

the class RecursiveActionTest method testSortTaskDemo.

/**
 * SortTask demo works as advertised
 */
public void testSortTaskDemo() {
    ThreadLocalRandom rnd = ThreadLocalRandom.current();
    long[] array = new long[1007];
    for (int i = 0; i < array.length; i++) array[i] = rnd.nextLong();
    long[] arrayClone = array.clone();
    testInvokeOnPool(mainPool(), new SortTask(array));
    Arrays.sort(arrayClone);
    assertTrue(Arrays.equals(array, arrayClone));
}
Also used : ThreadLocalRandom(java8.util.concurrent.ThreadLocalRandom)

Aggregations

ThreadLocalRandom (java8.util.concurrent.ThreadLocalRandom)48 LongAdder (java8.util.concurrent.atomic.LongAdder)18 Collection (java.util.Collection)9 Test (org.testng.annotations.Test)9 ArrayList (java.util.ArrayList)8 LinkedList (java.util.LinkedList)8 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)8 ArrayDeque (java.util.ArrayDeque)7 Deque (java.util.Deque)7 HashSet (java.util.HashSet)7 List (java.util.List)7 BlockingDeque (java.util.concurrent.BlockingDeque)7 LinkedBlockingDeque (java.util.concurrent.LinkedBlockingDeque)7 ConcurrentModificationException (java.util.ConcurrentModificationException)6 Set (java.util.Set)6 ConcurrentLinkedQueue (java.util.concurrent.ConcurrentLinkedQueue)6 CopyOnWriteArraySet (java.util.concurrent.CopyOnWriteArraySet)6 AtomicLong (java.util.concurrent.atomic.AtomicLong)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 Spliterator (java8.util.Spliterator)6