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(); } }}; }
private static void runTest() throws Exception { final Phaser p = new Phaser(2); blocking = new BlockingThread(p); blocking.start(); blocked = new BlockedThread(p); blocked.start(); try { blocking.join(); testOk = checkBlocked(); p.arriveAndAwaitAdvance(); // #5 } catch (InterruptedException e) { System.err.println("Unexpected exception."); e.printStackTrace(System.err); throw e; } }
static Reader interruptibleReaderView(final StampedLock sl, final long timeout, final TimeUnit unit, final Phaser gate) { return new Reader("InterruptibleReaderView") { public void run() { if (gate != null ) toTheStartingGate(gate); final Lock rl = sl.asReadLock(); try { if (timeout < 0) rl.lockInterruptibly(); else rl.tryLock(timeout, unit); stamp(1L); // got the lock check(sl.isReadLocked()); check(!sl.isWriteLocked()); } catch (Throwable x) { thrown(x); } finally { if (stamp() != 0L) rl.unlock(); } }}; }
/** * arriveAndDeregister does not wait for others to arrive at barrier */ public void testArrive2() { final Phaser phaser = new Phaser(); assertEquals(0, phaser.register()); List<Thread> threads = new ArrayList<>(); for (int i = 0; i < 10; i++) { assertEquals(0, phaser.register()); threads.add(newStartedThread(new CheckedRunnable() { public void realRun() { assertEquals(0, phaser.arriveAndDeregister()); }})); } for (Thread thread : threads) awaitTermination(thread); assertState(phaser, 0, 1, 1); assertEquals(0, phaser.arrive()); assertState(phaser, 1, 1, 1); }
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();}}; }
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); }
private static Iterator<Arriver> arriverIterator(final Phaser phaser) { return new Iterator<Arriver>() { int i = 0; public boolean hasNext() { return true; } public Arriver next() { switch ((i++)&7) { case 0: case 4: return arriver(phaser); case 1: case 5: return awaiter(phaser); case 2: case 6: case 7: return awaiter(phaser, -1, SECONDS); default: return awaiter(phaser, 30, SECONDS); }} public void remove() {throw new UnsupportedOperationException();}}; }
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()); } }}; }
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()); } }}; }
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();}}; }
/** * awaitAdvance continues waiting if interrupted before waiting */ public void testAwaitAdvanceAfterInterrupt() { 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()); assertEquals(0, phaser.arrive()); pleaseArrive.countDown(); assertTrue(Thread.currentThread().isInterrupted()); assertEquals(1, phaser.awaitAdvance(0)); assertTrue(Thread.interrupted()); }}); await(pleaseArrive); assertThreadBlocks(t, Thread.State.WAITING); assertEquals(0, phaser.arrive()); awaitTermination(t); Thread.currentThread().interrupt(); assertEquals(1, phaser.awaitAdvance(0)); assertTrue(Thread.interrupted()); }
/** * awaitAdvance continues waiting if interrupted while waiting */ public void testAwaitAdvanceBeforeInterrupt() { final Phaser phaser = new Phaser(); assertEquals(0, phaser.register()); final CountDownLatch pleaseArrive = new CountDownLatch(1); Thread t = newStartedThread(new CheckedRunnable() { public void realRun() { assertEquals(0, phaser.register()); assertEquals(0, phaser.arrive()); assertFalse(Thread.currentThread().isInterrupted()); pleaseArrive.countDown(); assertEquals(1, phaser.awaitAdvance(0)); assertTrue(Thread.interrupted()); }}); await(pleaseArrive); assertThreadBlocks(t, Thread.State.WAITING); t.interrupt(); assertEquals(0, phaser.arrive()); awaitTermination(t); Thread.currentThread().interrupt(); assertEquals(1, phaser.awaitAdvance(0)); assertTrue(Thread.interrupted()); }
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 ex) { unexpected(ex); } equal(phaser.getUnarrivedParties(), unarriverParties); equal(phaser.getRegisteredParties(), registeredParties); }
void test(String[] args) throws Throwable { final Phaser parent = new Phaser(); final Phaser child1 = new Phaser(parent); final Phaser child2 = new Phaser(parent); Thread t1 = new Thread(runner(child1)); Thread t2 = new Thread(runner(child2)); t1.start(); t2.start(); for (int prevPhase = 0, phase; ; prevPhase = phase) { phase = child2.getPhase(); check(phase >= prevPhase); if (System.nanoTime() - quittingTimeNanos > 0) { System.err.printf("phase=%d%n", phase); child1.forceTermination(); break; } } t1.join(); t2.join(); }
/** * register on a subphaser that is currently empty succeeds, even * in the presence of another non-empty subphaser */ public void testRegisterEmptySubPhaser() { Phaser root = new Phaser(); Phaser child1 = new Phaser(root, 1); Phaser child2 = new Phaser(root, 0); assertEquals(0, child2.register()); assertState(root, 0, 2, 2); assertState(child1, 0, 1, 1); assertState(child2, 0, 1, 1); assertEquals(0, child2.arriveAndDeregister()); assertState(root, 0, 1, 1); assertState(child1, 0, 1, 1); assertState(child2, 0, 0, 0); assertEquals(0, child2.register()); assertEquals(0, child2.arriveAndDeregister()); assertState(root, 0, 1, 1); assertState(child1, 0, 1, 1); assertState(child2, 0, 0, 0); assertEquals(0, child1.arriveAndDeregister()); assertTerminated(root, 1); assertTerminated(child1, 1); assertTerminated(child2, 1); }
/** * Start the command line runner. * * @return a CommandLineRunner */ @Bean public CommandLineRunner run() { return args -> { String host = "localhost"; String path = "/greeting?name=JavaLand"; jettyClientDemo.performAsyncHttpRequest(host, http2Port, path); jettyClientDemo.performDefaultHttpRequest(host, http2Port, path); jettyClientDemo.performHttpRequestReceivePush(host, http2Port, path, new FuturePromise<>(), new Phaser(2)); }; }
/** * Perform an http request and wait for a possibly incoming push promise. * * @param host the hostname * @param port the port * @param path the request path * @param sessionPromise the session promise object * @param phaser the phaser * @throws Exception may occur when client is started or stopped */ public void performHttpRequestReceivePush( String host, int port, String path, FuturePromise<Session> sessionPromise, Phaser phaser) throws Exception { http2Client.addBean(sslContextFactory); http2Client.start(); http2Client.connect(sslContextFactory, new InetSocketAddress(host, port), new ServerSessionListener.Adapter(), sessionPromise); Session session = sessionPromise.get(5, TimeUnit.SECONDS); HttpFields requestFields = new HttpFields(); requestFields.put("User-Agent", http2Client .getClass() .getName() + "/" + Jetty.VERSION); MetaData.Request metaData = new MetaData.Request("GET", new HttpURI("https://" + host + ":" + port + path), HttpVersion.HTTP_2, requestFields); HeadersFrame headersFrame = new HeadersFrame(metaData, null, true); session.newStream(headersFrame, new Promise.Adapter<>(), new StreamListener(phaser)); phaser.awaitAdvanceInterruptibly(phaser.arrive(), 5, TimeUnit.SECONDS); http2Client.stop(); }
private static Arriver arriver(final Phaser phaser) { return new Arriver() { public void run() { toTheStartingGate(); try { phase(phaser.arrive()); } catch (Throwable result) { result(result); }}}; }
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(); } } } }
@Before public void setUp() { httpClient = mock(HttpClient.class); HTTP2Client http2Client = mock(HTTP2Client.class); contentResponse = mock(ContentResponse.class); request = mock(Request.class); SslContextFactory sslContextFactory = mock(SslContextFactory.class); session = mock(Session.class); phaser = mock(Phaser.class); sut = new JettyClientDemo(httpClient, http2Client, sslContextFactory); }
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(); }
/** * arriveAndDeregister does not wait for others to arrive at barrier */ public void testArriveAndDeregister() { final Phaser phaser = new Phaser(1); for (int i = 0; i < 10; i++) { assertState(phaser, 0, 1, 1); assertEquals(0, phaser.register()); assertState(phaser, 0, 2, 2); assertEquals(0, phaser.arriveAndDeregister()); assertState(phaser, 0, 1, 1); } assertEquals(0, phaser.arriveAndDeregister()); assertTerminated(phaser, 1); }
@Test public void reporterAfterCloseNoThrow() { final MockM3Server server = new MockM3Server(new Phaser(), true, socketAddress); Thread serverThread = new Thread(new Runnable() { @Override public void run() { server.serve(); } }); try { serverThread.start(); M3Reporter reporter = new M3Reporter.Builder(socketAddress) .service("test-service") .commonTags(DEFAULT_TAGS) .maxQueueSize(MAX_QUEUE_SIZE) .maxPacketSizeBytes(MAX_PACKET_SIZE_BYTES) .build(); reporter.close(); reporter.reportGauge("my-gauge", null, 4.2); reporter.flush(); } finally { server.close(); } }
Runnable runner(final Phaser p) { return new CheckedRunnable() { public void realRun() { int prevPhase = p.register(); while (!p.isTerminated()) { int phase = p.awaitAdvance(p.arrive()); if (phase < 0) return; equal(phase, (prevPhase + 1) & Integer.MAX_VALUE); int ph = p.getPhase(); check(ph < 0 || ph == phase); prevPhase = phase; } }}; }
/** * 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); }
/** * Main method of the example * @param args */ public static void main(String[] args) { // Creates a Phaser with three participants Phaser phaser=new Phaser(3); // Creates 3 FileSearch objects. Each of them search in different directory FileSearch system=new FileSearch("C:\\Windows", "log", phaser); FileSearch apps=new FileSearch("C:\\Program Files","log",phaser); FileSearch documents=new FileSearch("C:\\Documents And Settings","log",phaser); // Creates a thread to run the system FileSearch and starts it Thread systemThread=new Thread(system,"System"); systemThread.start(); // Creates a thread to run the apps FileSearch and starts it Thread appsThread=new Thread(apps,"Apps"); appsThread.start(); // Creates a thread to run the documents FileSearch and starts it Thread documentsThread=new Thread(documents,"Documents"); documentsThread.start(); try { systemThread.join(); appsThread.join(); documentsThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.printf("Terminated: %s\n",phaser.isTerminated()); }
/** * arrive() returns a negative number if the Phaser is terminated */ public void testArrive3() { Phaser phaser = new Phaser(1); phaser.forceTermination(); assertTerminated(phaser, 0, 1); assertEquals(0, phaser.getPhase() + Integer.MIN_VALUE); assertTrue(phaser.arrive() < 0); assertTrue(phaser.register() < 0); assertTrue(phaser.arriveAndDeregister() < 0); assertTrue(phaser.awaitAdvance(1) < 0); assertTrue(phaser.getPhase() < 0); }
/** * register() will increment the number of unarrived parties by * one and not affect its arrived parties */ public void testRegister1() { Phaser phaser = new Phaser(); assertState(phaser, 0, 0, 0); assertEquals(0, phaser.register()); assertState(phaser, 0, 1, 1); }
static Reader reader(final StampedLock sl, final Phaser gate) { return new Reader() { public void run() { if (gate != null ) toTheStartingGate(gate); stamp(sl.readLock()); try { check(sl.validate(stamp())); check(sl.isReadLocked()); check(!sl.isWriteLocked()); } finally { sl.unlockRead(stamp()); } }}; }
/** * 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(); }
/** * arriveAndDeregister returns the phase in which it leaves the * phaser in after deregistration */ public void testArriveAndDeregister6() { final Phaser phaser = new Phaser(2); Thread t = newStartedThread(new CheckedRunnable() { public void realRun() { assertEquals(0, phaser.arrive()); }}); assertEquals(1, phaser.arriveAndAwaitAdvance()); assertState(phaser, 1, 2, 2); assertEquals(1, phaser.arriveAndDeregister()); assertState(phaser, 1, 1, 1); assertEquals(1, phaser.arriveAndDeregister()); assertTerminated(phaser, 2); awaitTermination(t); }
static void syncTest(int nthreads, int incs) { System.out.print("Synchronized "); Phaser phaser = new Phaser(nthreads + 1); SynchronizedDoubleAdder a = new SynchronizedDoubleAdder(); for (int i = 0; i < nthreads; ++i) pool.execute(new SyncTask(a, phaser, incs)); report(nthreads, incs, timeTasks(phaser), a.sum()); }
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()); }
private static Awaiter awaiter(final Phaser phaser, final long timeout, final TimeUnit unit) { return new Awaiter("InterruptibleWaiter") { public void run() { toTheStartingGate(); try { if (timeout < 0) phase(phaser.awaitAdvanceInterruptibly(phaser.arrive())); else phase(phaser.awaitAdvanceInterruptibly(phaser.arrive(), timeout, unit)); } catch (Throwable result) { result(result); }}}; }
static void casTest(int nthreads, int incs) { System.out.print("AtomicLong "); Phaser phaser = new Phaser(nthreads + 1); AtomicLong a = new AtomicLong(); for (int i = 0; i < nthreads; ++i) pool.execute(new CasTask(a, phaser, incs)); report(nthreads, incs, timeTasks(phaser), a.get()); }
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()); }
public static void main(String[] args) throws Exception { List<NetworkInterface> toTest = getNetworkInterfacesAsStream() .filter(hasHardwareAddress) .collect(Collectors.toList()); ExecutorService executor = Executors.newFixedThreadPool(NUM_THREADS); for (NetworkInterface ni : toTest) { Phaser startingGate = new Phaser(NUM_THREADS); System.out.println("Testing: " + ni.getName()); List<Callable<Exception>> list = new ArrayList<>(); for (int i = 0; i < NUM_THREADS; i++) list.add(new GetMacAddress(ni, ni.getName() + "-Thread-" + i, startingGate)); List<Future<Exception>> futures = executor.invokeAll(list); for (Future<Exception> f : futures) { if (f.get() != null) f.get().printStackTrace(System.out); } if (failed) break; } executor.shutdownNow(); if (!failed) { System.out.println("PASSED - Finished all threads"); } else { throw new RuntimeException("Failed"); } }
/** * arrive() on a registered phaser increments phase. */ public void testArrive1() { Phaser phaser = new Phaser(1); assertState(phaser, 0, 1, 1); assertEquals(0, phaser.arrive()); assertState(phaser, 1, 1, 1); }