Search in sources :

Example 16 with Phaser

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

the class PhaserTest method testAwaitAdvance5.

/**
 * awaitAdvance returns the current phase
 */
public void testAwaitAdvance5() {
    final Phaser phaser = new Phaser(1);
    assertEquals(1, phaser.awaitAdvance(phaser.arrive()));
    assertEquals(1, phaser.getPhase());
    assertEquals(1, phaser.register());
    List<Thread> threads = new ArrayList<>();
    for (int i = 0; i < 8; i++) {
        final CountDownLatch latch = new CountDownLatch(1);
        final boolean goesFirst = ((i & 1) == 0);
        threads.add(newStartedThread(new CheckedRunnable() {

            public void realRun() {
                if (goesFirst)
                    latch.countDown();
                else
                    await(latch);
                phaser.arrive();
            }
        }));
        if (goesFirst)
            await(latch);
        else
            latch.countDown();
        assertEquals(i + 2, phaser.awaitAdvance(phaser.arrive()));
        assertEquals(i + 2, phaser.getPhase());
    }
    for (Thread thread : threads) awaitTermination(thread);
}
Also used : ArrayList(java.util.ArrayList) Phaser(java8.util.concurrent.Phaser) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 17 with Phaser

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

the class PhaserTest method testArriveAndDeregister5.

/**
 * arriveAndDeregister deregisters one party from its parent when
 * the number of parties of root is nonzero after deregistration.
 */
public void testArriveAndDeregister5() {
    Phaser root = new Phaser();
    Phaser parent = new Phaser(root);
    Phaser child = new Phaser(parent);
    assertState(root, 0, 0, 0);
    assertState(parent, 0, 0, 0);
    assertState(child, 0, 0, 0);
    assertEquals(0, child.register());
    assertState(root, 0, 1, 1);
    assertState(parent, 0, 1, 1);
    assertState(child, 0, 1, 1);
    assertEquals(0, child.arriveAndDeregister());
    assertTerminated(child, 1);
    assertTerminated(parent, 1);
    assertTerminated(root, 1);
}
Also used : Phaser(java8.util.concurrent.Phaser)

Example 18 with Phaser

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

the class LongAccumulatorTest method testAccumulateAndGetMT.

/**
 * accumulates by multiple threads produce correct result
 */
public void testAccumulateAndGetMT() {
    final LongAccumulator acc = new LongAccumulator((x, y) -> x + y, 0L);
    final int nThreads = ThreadLocalRandom.current().nextInt(1, 5);
    final Phaser phaser = new Phaser(nThreads + 1);
    final int incs = 1_000_000;
    // Gauss
    final long total = nThreads * incs / 2L * (incs - 1);
    final Runnable task = () -> {
        phaser.arriveAndAwaitAdvance();
        for (int i = 0; i < incs; i++) {
            acc.accumulate((long) i);
            assertTrue(acc.get() <= total);
        }
        phaser.arrive();
    };
    final ExecutorService p = Executors.newCachedThreadPool();
    PoolCleaner cleaner = null;
    try {
        cleaner = cleaner(p);
        for (int i = nThreads; i-- > 0; ) /**/
        p.execute(task);
        phaser.arriveAndAwaitAdvance();
        phaser.arriveAndAwaitAdvance();
        assertEquals(total, acc.get());
    } finally {
        if (cleaner != null) {
            cleaner.close();
        }
    }
}
Also used : LongAccumulator(java8.util.concurrent.atomic.LongAccumulator) ExecutorService(java.util.concurrent.ExecutorService) Phaser(java8.util.concurrent.Phaser)

Example 19 with Phaser

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

the class LongAdderDemo method adderTest.

static void adderTest(int nthreads, int incs) {
    System.out.print("LongAdder  ");
    Phaser phaser = new Phaser(nthreads + 1);
    LongAdder a = new LongAdder();
    for (int i = 0; i < nthreads; ++i) pool.execute(new AdderTask(a, phaser, incs));
    report(nthreads, incs, timeTasks(phaser), a.sum());
}
Also used : LongAdder(java8.util.concurrent.atomic.LongAdder) Phaser(java8.util.concurrent.Phaser)

Example 20 with Phaser

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

the class Basic method realMain.

private static void realMain(String[] args) throws Throwable {
    SimpleTimer timer = new SimpleTimer();
    Thread.currentThread().setName("mainThread");
    // ----------------------------------------------------------------
    System.out.print("Normal use: ");
    // ----------------------------------------------------------------
    try {
        Phaser phaser = new Phaser(3);
        equal(phaser.getRegisteredParties(), 3);
        equal(phaser.getArrivedParties(), 0);
        equal(phaser.getPhase(), 0);
        check(phaser.getRoot().equals(phaser));
        equal(phaser.getParent(), null);
        check(!phaser.isTerminated());
        Iterator<Arriver> arrivers = arriverIterator(phaser);
        int phase = 0;
        for (int i = 0; i < 10; i++) {
            equal(phaser.getPhase(), phase++);
            Arriver a1 = arrivers.next();
            a1.start();
            Arriver a2 = arrivers.next();
            a2.start();
            toTheStartingGate();
            phaser.arriveAndAwaitAdvance();
            a1.join();
            a2.join();
            checkResult(a1, null);
            checkResult(a2, null);
            check(!phaser.isTerminated());
            equal(phaser.getRegisteredParties(), 3);
            equal(phaser.getArrivedParties(), 0);
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    timer.printElapsed();
    // ----------------------------------------------------------------
    System.out.print("One thread interrupted: ");
    // ----------------------------------------------------------------
    try {
        Phaser phaser = new Phaser(3);
        Iterator<Arriver> arrivers = arriverIterator(phaser);
        int phase = phaser.getPhase();
        for (int i = 0; i < 10; i++) {
            check(phaser.getPhase() == phase);
            Awaiter a1 = awaiter(phaser, 30, SECONDS);
            a1.start();
            Arriver a2 = arrivers.next();
            a2.start();
            toTheStartingGate();
            a1.interrupt();
            a1.join();
            phaser.arriveAndAwaitAdvance();
            a2.join();
            checkResult(a1, InterruptedException.class);
            checkResult(a2, null);
            check(!phaser.isTerminated());
            equal(phaser.getRegisteredParties(), 3);
            equal(phaser.getArrivedParties(), 0);
            phase++;
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    timer.printElapsed();
    // ----------------------------------------------------------------
    System.out.print("Phaser is terminated while threads are waiting: ");
    // ----------------------------------------------------------------
    try {
        for (int i = 0; i < 10; i++) {
            Phaser phaser = new Phaser(3);
            Iterator<Awaiter> awaiters = awaiterIterator(phaser);
            Arriver a1 = awaiters.next();
            a1.start();
            Arriver a2 = awaiters.next();
            a2.start();
            toTheStartingGate();
            while (phaser.getArrivedParties() < 2) Thread.yield();
            equal(0, phaser.getPhase());
            phaser.forceTermination();
            a1.join();
            a2.join();
            equal(0 + Integer.MIN_VALUE, a1.phase);
            equal(0 + Integer.MIN_VALUE, a2.phase);
            int arrivedParties = phaser.getArrivedParties();
            checkTerminated(phaser);
            equal(phaser.getArrivedParties(), arrivedParties);
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    timer.printElapsed();
    // ----------------------------------------------------------------
    System.out.print("Adds new unarrived parties to this phaser: ");
    // ----------------------------------------------------------------
    try {
        Phaser phaser = new Phaser(1);
        Iterator<Arriver> arrivers = arriverIterator(phaser);
        LinkedList<Arriver> arriverList = new LinkedList<>();
        int phase = phaser.getPhase();
        for (int i = 1; i < 5; i++) {
            startingGate = new Phaser(1 + (3 * i));
            check(phaser.getPhase() == phase);
            // register 3 more
            phaser.register();
            phaser.register();
            phaser.register();
            for (int z = 0; z < (3 * i); z++) {
                arriverList.add(arrivers.next());
            }
            for (Arriver arriver : arriverList) arriver.start();
            toTheStartingGate();
            phaser.arriveAndAwaitAdvance();
            for (Arriver arriver : arriverList) {
                arriver.join();
                checkResult(arriver, null);
            }
            equal(phaser.getRegisteredParties(), 1 + (3 * i));
            equal(phaser.getArrivedParties(), 0);
            arriverList.clear();
            phase++;
        }
        startingGate = new Phaser(3);
    } catch (Throwable t) {
        unexpected(t);
    }
    timer.printElapsed();
    // ----------------------------------------------------------------
    System.out.print("One thread timed out: ");
    // ----------------------------------------------------------------
    try {
        Phaser phaser = new Phaser(3);
        Iterator<Arriver> arrivers = arriverIterator(phaser);
        for (long timeout : new long[] { 0L, 12L }) {
            Awaiter a1 = awaiter(phaser, timeout, MILLISECONDS);
            a1.start();
            Arriver a2 = arrivers.next();
            a2.start();
            toTheStartingGate();
            a1.join();
            checkResult(a1, TimeoutException.class);
            phaser.arrive();
            a2.join();
            checkResult(a2, null);
            check(!phaser.isTerminated());
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    timer.printElapsed();
    // ----------------------------------------------------------------
    System.out.print("Barrier action completed normally: ");
    // ----------------------------------------------------------------
    try {
        final AtomicInteger count = new AtomicInteger(0);
        final Phaser[] kludge = new Phaser[1];
        Phaser phaser = new Phaser(3) {

            @Override
            protected boolean onAdvance(int phase, int registeredParties) {
                int countPhase = count.getAndIncrement();
                equal(countPhase, phase);
                equal(kludge[0].getPhase(), phase);
                equal(kludge[0].getRegisteredParties(), registeredParties);
                if (phase >= 3)
                    // terminate
                    return true;
                return false;
            }
        };
        kludge[0] = phaser;
        equal(phaser.getRegisteredParties(), 3);
        Iterator<Awaiter> awaiters = awaiterIterator(phaser);
        for (int i = 0; i < 4; i++) {
            Awaiter a1 = awaiters.next();
            a1.start();
            Awaiter a2 = awaiters.next();
            a2.start();
            toTheStartingGate();
            while (phaser.getArrivedParties() < 2) Thread.yield();
            phaser.arrive();
            a1.join();
            a2.join();
            checkResult(a1, null);
            checkResult(a2, null);
            equal(count.get(), i + 1);
            if (i < 3) {
                check(!phaser.isTerminated());
                equal(phaser.getRegisteredParties(), 3);
                equal(phaser.getArrivedParties(), 0);
                equal(phaser.getUnarrivedParties(), 3);
                equal(phaser.getPhase(), count.get());
            } else
                checkTerminated(phaser);
        }
    } catch (Throwable t) {
        unexpected(t);
    }
    timer.printElapsed();
}
Also used : LinkedList(java.util.LinkedList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Phaser(java8.util.concurrent.Phaser)

Aggregations

Phaser (java8.util.concurrent.Phaser)51 CountDownLatch (java.util.concurrent.CountDownLatch)9 ArrayList (java.util.ArrayList)8 ExecutorService (java.util.concurrent.ExecutorService)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 LinkedList (java.util.LinkedList)2 Executors (java.util.concurrent.Executors)2 MILLISECONDS (java.util.concurrent.TimeUnit.MILLISECONDS)2 AtomicLong (java.util.concurrent.atomic.AtomicLong)2 Test (org.testng.annotations.Test)2 Array (java.lang.reflect.Array)1 ArrayDeque (java.util.ArrayDeque)1 Arrays (java.util.Arrays)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 List (java.util.List)1