java.util.concurrent.Phaser Java Examples
The following examples show how to use
java.util.concurrent.Phaser.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Basic.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
static Writer interruptibleWriter(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Writer("InterruptibleWriter") { public void run() { if (gate != null ) toTheStartingGate(gate); try { if (timeout < 0) stamp(sl.writeLockInterruptibly()); else stamp(sl.tryWriteLock(timeout, unit)); check(sl.validate(stamp())); check(!sl.isReadLocked()); check(sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) sl.unlockWrite(stamp()); } }}; }
Example #2
Source File: AutoShutdown.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
private static void realMain(String[] args) throws Throwable { final Phaser phaser = new Phaser(3); Runnable trivialRunnable = new Runnable() { public void run() { phaser.arriveAndAwaitAdvance(); } }; int count0 = Thread.activeCount(); Executor e1 = newSingleThreadExecutor(); Executor e2 = newSingleThreadExecutor(defaultThreadFactory()); e1.execute(trivialRunnable); e2.execute(trivialRunnable); phaser.arriveAndAwaitAdvance(); equal(Thread.activeCount(), count0 + 2); e1 = e2 = null; for (int i = 0; i < 10 && Thread.activeCount() > count0; i++) tryWaitForFinalizersToRun(); for (int i = 0; i < 10; ++i) { // give JVM a chance to settle. if (Thread.activeCount() == count0) return; Thread.sleep(1000); } equal(Thread.activeCount(), count0); }
Example #3
Source File: Basic.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
static Iterator<Writer> writerIterator(final StampedLock sl, final Phaser gate) { return new Iterator<Writer>() { int i = 0; boolean view = false; public boolean hasNext() { return true; } public Writer next() { switch ((i++)&7) { case 1: case 4: case 7: return writer(sl, gate, view ^= true); case 2: case 5: return interruptibleWriter(sl, -1, SECONDS, gate, view ^= true); default: return interruptibleWriter(sl, LONG_DELAY_MS, MILLISECONDS, gate, view ^= true); }} public void remove() {throw new UnsupportedOperationException();}}; }
Example #4
Source File: Basic.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
static Reader interruptibleReader(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Reader("InterruptibleReader") { public void run() { if (gate != null ) toTheStartingGate(gate); try { if (timeout < 0) stamp(sl.readLockInterruptibly()); else stamp(sl.tryReadLock(timeout, unit)); check(sl.validate(stamp())); check(sl.isReadLocked()); check(!sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) sl.unlockRead(stamp()); } }}; }
Example #5
Source File: AutoShutdown.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
private static void realMain(String[] args) throws Throwable { final Phaser phaser = new Phaser(3); Runnable trivialRunnable = new Runnable() { public void run() { phaser.arriveAndAwaitAdvance(); } }; int count0 = Thread.activeCount(); Executor e1 = newSingleThreadExecutor(); Executor e2 = newSingleThreadExecutor(defaultThreadFactory()); e1.execute(trivialRunnable); e2.execute(trivialRunnable); phaser.arriveAndAwaitAdvance(); equal(Thread.activeCount(), count0 + 2); e1 = e2 = null; for (int i = 0; i < 10 && Thread.activeCount() > count0; i++) tryWaitForFinalizersToRun(); for (int i = 0; i < 10; ++i) { // give JVM a chance to settle. if (Thread.activeCount() == count0) return; Thread.sleep(1000); } equal(Thread.activeCount(), count0); }
Example #6
Source File: Basic.java From hottub with GNU General Public License v2.0 | 6 votes |
static Iterator<Reader> readerIterator(final StampedLock sl, final Phaser gate) { return new Iterator<Reader>() { int i = 0; boolean view = false; public boolean hasNext() { return true; } public Reader next() { switch ((i++)&7) { case 1: case 4: case 7: return reader(sl, gate, view ^= true); case 2: case 5: return interruptibleReader(sl, -1, SECONDS, gate, view ^= true); default: return interruptibleReader(sl, 30, SECONDS, gate, view ^= true); }} public void remove() {throw new UnsupportedOperationException();}}; }
Example #7
Source File: Basic.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
static Writer interruptibleWriterView(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Writer("InterruptibleWriterView") { public void run() { if (gate != null ) toTheStartingGate(gate); Lock wl = sl.asWriteLock(); try { if (timeout < 0) wl.lockInterruptibly(); else wl.tryLock(timeout, unit); stamp(1L); // got the lock check(!sl.isReadLocked()); check(sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) wl.unlock(); } }}; }
Example #8
Source File: Basic.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
static Iterator<Writer> writerIterator(final StampedLock sl, final Phaser gate) { return new Iterator<Writer>() { int i = 0; boolean view = false; public boolean hasNext() { return true; } public Writer next() { switch ((i++)&7) { case 1: case 4: case 7: return writer(sl, gate, view ^= true); case 2: case 5: return interruptibleWriter(sl, -1, SECONDS, gate, view ^= true); default: return interruptibleWriter(sl, 30, SECONDS, gate, view ^= true); }} public void remove() {throw new UnsupportedOperationException();}}; }
Example #9
Source File: Basic.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
static Reader interruptibleReader(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Reader("InterruptibleReader") { public void run() { if (gate != null ) toTheStartingGate(gate); try { if (timeout < 0) stamp(sl.readLockInterruptibly()); else stamp(sl.tryReadLock(timeout, unit)); check(sl.validate(stamp())); check(sl.isReadLocked()); check(!sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) sl.unlockRead(stamp()); } }}; }
Example #10
Source File: Basic.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
static Writer interruptibleWriter(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Writer("InterruptibleWriter") { public void run() { if (gate != null ) toTheStartingGate(gate); try { if (timeout < 0) stamp(sl.writeLockInterruptibly()); else stamp(sl.tryWriteLock(timeout, unit)); check(sl.validate(stamp())); check(!sl.isReadLocked()); check(sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) sl.unlockWrite(stamp()); } }}; }
Example #11
Source File: Basic.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
private static void checkTerminated(final Phaser phaser) { check(phaser.isTerminated()); int unarriverParties = phaser.getUnarrivedParties(); int registeredParties = phaser.getRegisteredParties(); int phase = phaser.getPhase(); check(phase < 0); equal(phase, phaser.arrive()); equal(phase, phaser.arriveAndDeregister()); equal(phase, phaser.arriveAndAwaitAdvance()); equal(phase, phaser.bulkRegister(10)); equal(phase, phaser.register()); try { equal(phase, phaser.awaitAdvanceInterruptibly(0)); equal(phase, phaser.awaitAdvanceInterruptibly(0, 10, SECONDS)); } catch (Exception ie) { unexpected(ie); } equal(phaser.getUnarrivedParties(), unarriverParties); equal(phaser.getRegisteredParties(), registeredParties); }
Example #12
Source File: Basic.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
static Writer interruptibleWriter(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Writer("InterruptibleWriter") { public void run() { if (gate != null ) toTheStartingGate(gate); try { if (timeout < 0) stamp(sl.writeLockInterruptibly()); else stamp(sl.tryWriteLock(timeout, unit)); check(sl.validate(stamp())); check(!sl.isReadLocked()); check(sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) sl.unlockWrite(stamp()); } }}; }
Example #13
Source File: Basic.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
static Iterator<Writer> writerIterator(final StampedLock sl, final Phaser gate) { return new Iterator<Writer>() { int i = 0; boolean view = false; public boolean hasNext() { return true; } public Writer next() { switch ((i++)&7) { case 1: case 4: case 7: return writer(sl, gate, view ^= true); case 2: case 5: return interruptibleWriter(sl, -1, SECONDS, gate, view ^= true); default: return interruptibleWriter(sl, 30, SECONDS, gate, view ^= true); }} public void remove() {throw new UnsupportedOperationException();}}; }
Example #14
Source File: PhaserTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * arriveAndAwaitAdvance continues waiting if interrupted before waiting */ public void testArriveAndAwaitAdvanceAfterInterrupt() { final Phaser phaser = new Phaser(); assertEquals(0, phaser.register()); final CountDownLatch pleaseArrive = new CountDownLatch(1); Thread t = newStartedThread(new CheckedRunnable() { public void realRun() { Thread.currentThread().interrupt(); assertEquals(0, phaser.register()); pleaseArrive.countDown(); assertTrue(Thread.currentThread().isInterrupted()); assertEquals(1, phaser.arriveAndAwaitAdvance()); assertTrue(Thread.interrupted()); }}); await(pleaseArrive); waitForThreadToEnterWaitState(t); Thread.currentThread().interrupt(); assertEquals(1, phaser.arriveAndAwaitAdvance()); assertTrue(Thread.interrupted()); awaitTermination(t); }
Example #15
Source File: PhaserTest.java From j2objc with Apache License 2.0 | 6 votes |
/** * arriveAndAwaitAdvance continues waiting if interrupted before waiting */ public void testArriveAndAwaitAdvanceAfterInterrupt() { final Phaser phaser = new Phaser(); assertEquals(0, phaser.register()); final CountDownLatch pleaseArrive = new CountDownLatch(1); Thread t = newStartedThread(new CheckedRunnable() { public void realRun() { Thread.currentThread().interrupt(); assertEquals(0, phaser.register()); pleaseArrive.countDown(); assertTrue(Thread.currentThread().isInterrupted()); assertEquals(1, phaser.arriveAndAwaitAdvance()); assertTrue(Thread.interrupted()); }}); await(pleaseArrive); waitForThreadToEnterWaitState(t); Thread.currentThread().interrupt(); assertEquals(1, phaser.arriveAndAwaitAdvance()); assertTrue(Thread.interrupted()); awaitTermination(t); }
Example #16
Source File: Basic.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
static Iterator<Reader> readerIterator(final StampedLock sl, final Phaser gate) { return new Iterator<Reader>() { int i = 0; boolean view = false; public boolean hasNext() { return true; } public Reader next() { switch ((i++)&7) { case 1: case 4: case 7: return reader(sl, gate, view ^= true); case 2: case 5: return interruptibleReader(sl, -1, SECONDS, gate, view ^= true); default: return interruptibleReader(sl, 30, SECONDS, gate, view ^= true); }} public void remove() {throw new UnsupportedOperationException();}}; }
Example #17
Source File: Basic.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
static Writer interruptibleWriter(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Writer("InterruptibleWriter") { public void run() { if (gate != null ) toTheStartingGate(gate); try { if (timeout < 0) stamp(sl.writeLockInterruptibly()); else stamp(sl.tryWriteLock(timeout, unit)); check(sl.validate(stamp())); check(!sl.isReadLocked()); check(sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) sl.unlockWrite(stamp()); } }}; }
Example #18
Source File: Race.java From openjdk-8 with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws Exception { try (ServerSocket ss = new ServerSocket(0)) { final int port = ss.getLocalPort(); final Phaser phaser = new Phaser(THREADS + 1); for (int i=0; i<100; i++) { final Socket s = new Socket("localhost", port); s.setSoLinger(false, 0); try (Socket sa = ss.accept()) { sa.setSoLinger(false, 0); final InputStream is = s.getInputStream(); Thread[] threads = new Thread[THREADS]; for (int j=0; j<THREADS; j++) { threads[j] = new Thread() { public void run() { try { phaser.arriveAndAwaitAdvance(); while (is.read() != -1) Thread.sleep(50); } catch (Exception x) { if (!(x instanceof SocketException && x.getMessage().equalsIgnoreCase("socket closed"))) x.printStackTrace(); // ok, expect Socket closed } }}; } for (int j=0; j<100; j++) threads[j].start(); phaser.arriveAndAwaitAdvance(); s.close(); for (int j=0; j<100; j++) threads[j].join(); } } } }
Example #19
Source File: PhaserTest.java From j2objc with Apache License 2.0 | 5 votes |
/** * 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<Thread>(); 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); }
Example #20
Source File: SynchronizationStatistics.java From hottub with GNU General Public License v2.0 | 5 votes |
/** * Tests that waiting on a single monitor properly increases the waited * count by 1 and the waited time by a positive number. */ private static void testWaitingOnSimpleMonitor() throws Exception { System.out.println("testWaitingOnSimpleMonitor"); final Object lock1 = new Object(); final Phaser p = new Phaser(2); LockerThread lt = newLockerThread(new Runnable() { @Override public void run() { p.arriveAndAwaitAdvance(); // phase[1] synchronized(lock1) { System.out.println("[LockerThread obtained Lock1]"); try { lock1.wait(300); } catch (InterruptedException ex) { // ignore } p.arriveAndAwaitAdvance(); // phase[2] } p.arriveAndAwaitAdvance(); // phase[3] } }); lt.start(); ThreadInfo ti1 = mbean.getThreadInfo(lt.getId()); synchronized(lock1) { p.arriveAndAwaitAdvance(); // phase[1] waitForThreadState(lt, Thread.State.BLOCKED); } p.arriveAndAwaitAdvance(); // phase[2] testWaited(ti1, () -> mbean.getThreadInfo(lt.getId()), 1); p.arriveAndDeregister(); // phase[3] lt.join(); printok(); }
Example #21
Source File: PhaserTest.java From j2objc with Apache License 2.0 | 5 votes |
/** Checks state of unterminated phaser. */ protected void assertState(Phaser phaser, int phase, int parties, int unarrived) { assertEquals(phase, phaser.getPhase()); assertEquals(parties, phaser.getRegisteredParties()); assertEquals(unarrived, phaser.getUnarrivedParties()); assertEquals(parties - unarrived, phaser.getArrivedParties()); assertFalse(phaser.isTerminated()); }
Example #22
Source File: Basic.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
static Writer writer(final StampedLock sl, final Phaser gate) { return new Writer() { public void run() { if (gate != null ) toTheStartingGate(gate); try { stamp(sl.writeLock()); check(sl.validate(stamp())); check(!sl.isReadLocked()); check(sl.isWriteLocked()); } finally { sl.unlockWrite(stamp()); } }}; }
Example #23
Source File: Basic.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
static Reader interruptibleReader(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate, final boolean view) { return view ? interruptibleReaderView(sl, timeout, unit, gate) : interruptibleReader(sl, timeout, unit, gate); }
Example #24
Source File: BeamFnLoggingClient.java From beam with Apache License 2.0 | 5 votes |
public BeamFnLoggingClient( PipelineOptions options, Endpoints.ApiServiceDescriptor apiServiceDescriptor, Function<Endpoints.ApiServiceDescriptor, ManagedChannel> channelFactory) { this.apiServiceDescriptor = apiServiceDescriptor; this.inboundObserverCompletion = new CompletableFuture<>(); this.configuredLoggers = new ArrayList<>(); this.phaser = new Phaser(1); this.channel = channelFactory.apply(apiServiceDescriptor); // Reset the global log manager, get the root logger and remove the default log handlers. LogManager logManager = LogManager.getLogManager(); logManager.reset(); Logger rootLogger = logManager.getLogger(ROOT_LOGGER_NAME); for (Handler handler : rootLogger.getHandlers()) { rootLogger.removeHandler(handler); } // Use the passed in logging options to configure the various logger levels. SdkHarnessOptions loggingOptions = options.as(SdkHarnessOptions.class); if (loggingOptions.getDefaultSdkHarnessLogLevel() != null) { rootLogger.setLevel(LEVEL_CONFIGURATION.get(loggingOptions.getDefaultSdkHarnessLogLevel())); } if (loggingOptions.getSdkHarnessLogLevelOverrides() != null) { for (Map.Entry<String, SdkHarnessOptions.LogLevel> loggerOverride : loggingOptions.getSdkHarnessLogLevelOverrides().entrySet()) { Logger logger = Logger.getLogger(loggerOverride.getKey()); logger.setLevel(LEVEL_CONFIGURATION.get(loggerOverride.getValue())); configuredLoggers.add(logger); } } BeamFnLoggingGrpc.BeamFnLoggingStub stub = BeamFnLoggingGrpc.newStub(channel); inboundObserver = new LogControlObserver(); logRecordHandler = new LogRecordHandler(options.as(GcsOptions.class).getExecutorService()); logRecordHandler.setLevel(Level.ALL); outboundObserver = (CallStreamObserver<BeamFnApi.LogEntry.List>) stub.logging(inboundObserver); rootLogger.addHandler(logRecordHandler); }
Example #25
Source File: FluxTests.java From reactor-core with Apache License 2.0 | 5 votes |
@Test public void combineWithOneElement() throws InterruptedException, TimeoutException { AtomicReference<Object> ref = new AtomicReference<>(null); Phaser phaser = new Phaser(2); Flux<Object> s1 = Processors.more().replayLatestOrDefault(new Object()) .publishOn(asyncGroup); Flux<Object> s2 = Processors.more().replayLatestOrDefault(new Object()) .publishOn(asyncGroup); // The following works: //List<Flux<Object>> list = Arrays.collectList(s1); // The following fails: List<Flux<Object>> list = Arrays.asList(s1, s2); Flux.combineLatest(list, t -> t) .log() .doOnNext(obj -> { ref.set(obj); phaser.arrive(); }) .subscribe(); phaser.awaitAdvanceInterruptibly(phaser.arrive(), 1, TimeUnit.SECONDS); Assert.assertNotNull(ref.get()); }
Example #26
Source File: PhaserTest.java From openjdk-systemtest with Apache License 2.0 | 5 votes |
public PhaserHelperThread(Phaser phaserIn, boolean awaitOthersIn, int phaseToWaitForIn, boolean allowInterruptIn, boolean expectInterruptIn, boolean deregisterTestIn) { phaser = phaserIn; awaitOthers = awaitOthersIn; phaseToWaitFor = phaseToWaitForIn; allowInterrupt = allowInterruptIn; expectInterrupt = expectInterruptIn; deregisterTest = deregisterTestIn; // Register with the Phaser phaser.register(); }
Example #27
Source File: DoubleAdderDemo.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
static void adderTest(int nthreads, int incs) { System.out.print("DoubleAdder "); Phaser phaser = new Phaser(nthreads + 1); DoubleAdder a = new DoubleAdder(); for (int i = 0; i < nthreads; ++i) pool.execute(new AdderTask(a, phaser, incs)); report(nthreads, incs, timeTasks(phaser), a.sum()); }
Example #28
Source File: PhaserTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
/** * the phase number increments correctly when tripping the barrier */ public void testPhaseIncrement1() { for (int size = 1; size < nine; size++) { final Phaser phaser = new Phaser(size); for (int index = 0; index <= (1 << size); index++) { int phase = phaser.arrive(); assertTrue(index % size == 0 ? (index / size) == phase : index - (phase * size) > 0); } } }
Example #29
Source File: DoubleAdderDemo.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
static long timeTasks(Phaser phaser) { phaser.arriveAndAwaitAdvance(); long start = System.nanoTime(); phaser.arriveAndAwaitAdvance(); phaser.arriveAndAwaitAdvance(); return System.nanoTime() - start; }
Example #30
Source File: WriteCloseableDataStore.java From emodb with Apache License 2.0 | 5 votes |
@Inject public WriteCloseableDataStore(@ManagedDataStoreDelegate DataStore delegate, @ManagedTableBackingStoreDelegate TableBackingStore tableBackingStore, MetricRegistry metricRegistry) { _delegate = requireNonNull(delegate); _tableBackingStore = requireNonNull(tableBackingStore); _writesAccepted = true; _writerPhaser = new Phaser(1); _writesRejectedCounter = metricRegistry.counter(MetricRegistry.name("bv.emodb.sor", "WriteCloseableDataStore", "writesRejected")); }