Java Code Examples for java.util.concurrent.Semaphore#acquire()

The following examples show how to use java.util.concurrent.Semaphore#acquire() . 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: AbstractBroadcastEnd2EndTest.java    From joynr with Apache License 2.0 6 votes vote down vote up
@Ignore
@Test(timeout = CONST_DEFAULT_TEST_TIMEOUT)
public void subscribeToBroadcastMultipleOutputs() throws InterruptedException {
    final Semaphore broadcastReceived = new Semaphore(0);

    proxy.subscribeToLocationUpdateWithSpeedBroadcast(new testBroadcastInterface.LocationUpdateWithSpeedBroadcastAdapter() {

        @Override
        public void onReceive(GpsLocation location, Float speed) {
            assertEquals(expectedLocation, location);
            assertEquals(expectedSpeed, speed);
            broadcastReceived.release();
        }
    }, new MulticastSubscriptionQos());

    Thread.sleep(300);

    provider.fireLocationUpdateWithSpeed(expectedLocation, expectedSpeed);
    broadcastReceived.acquire();
}
 
Example 2
Source File: BannerViewCacheTests.java    From unity-ads-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testTriggerBannerErrorEvent() throws InterruptedException {
	BannerViewCache bannerViewCache = new BannerViewCache();
	final BannerView bannerView = new BannerView(_activityRule.getActivity(), "test", new UnityBannerSize(320, 50));
	final BannerErrorInfo bannerErrorInfo = new BannerErrorInfo("test error", BannerErrorCode.NATIVE_ERROR);
	String bannerAdId = bannerViewCache.addBannerView(bannerView);
	final Semaphore _errorSemaphore = new Semaphore(0);
	bannerView.setListener(new BannerView.Listener() {
		@Override
		public void onBannerFailedToLoad(BannerView bannerAdView, BannerErrorInfo _bannerErrorInfo) {
			assertEquals(bannerView, bannerAdView);
			assertEquals(bannerErrorInfo, _bannerErrorInfo);
			_errorSemaphore.release();
		}
	});
	bannerViewCache.triggerBannerErrorEvent(bannerAdId, bannerErrorInfo);
	_errorSemaphore.acquire();
}
 
Example 3
Source File: ArtifactsDiskCleanerTest.java    From gocd with Apache License 2.0 6 votes vote down vote up
@Test(timeout = 20 * 1000)
public void shouldTriggerCleanupWhenLimitReached() throws InterruptedException {
    serverConfig.setPurgeLimits(20.0, 30.0);
    final boolean[] artifactsDeletionTriggered = {false};
    final Thread[] artifactDeleterThread = {null};
    final Semaphore sem = new Semaphore(1);
    sem.acquire();
    artifactsDiskCleaner = new ArtifactsDiskCleaner(sysEnv, goConfigService, diskSpaceChecker, artifactService, stageService, configDbStateRepository) {
        @Override void deleteOldArtifacts() {
            artifactDeleterThread[0] = Thread.currentThread();
            artifactsDeletionTriggered[0] = true;
            sem.release();
        }
    };
    Thread cleaner = (Thread) ReflectionUtil.getField(artifactsDiskCleaner, "cleaner");
    while(true) {
        if (cleaner.getState().equals(Thread.State.WAITING)) {
            break;
        }
        Thread.sleep(5);
    }
    artifactsDiskCleaner.createFailure(new HttpOperationResult(), 10, 100);
    sem.acquire();
    assertThat(artifactsDeletionTriggered[0], is(true));
    assertThat(artifactDeleterThread[0], not(sameInstance(Thread.currentThread())));
}
 
Example 4
Source File: ChromiumSyncAdapter.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void onPerformSync(Account account, Bundle extras, String authority,
                          ContentProviderClient provider, SyncResult syncResult) {
    if (!DelayedSyncController.getInstance().shouldPerformSync(getContext(), extras, account)) {
        return;
    }

    // Browser startup is asynchronous, so we will need to wait for startup to finish.
    Semaphore semaphore = new Semaphore(0);

    // Configure the callback with all the data it needs.
    BrowserStartupController.StartupCallback callback =
            getStartupCallback(mApplication, account, extras, syncResult, semaphore);
    startBrowserProcess(callback, syncResult, semaphore);

    try {
        // Wait for startup to complete.
        semaphore.acquire();
    } catch (InterruptedException e) {
        Log.w(TAG, "Got InterruptedException when trying to request a sync.", e);
        // Using numIoExceptions so Android will treat this as a soft error.
        syncResult.stats.numIoExceptions++;
    }
}
 
Example 5
Source File: IOSSyslogListenerTest.java    From java-client with Apache License 2.0 6 votes vote down vote up
@Test
public void verifySyslogListenerCanBeAssigned() {
    final Semaphore messageSemaphore = new Semaphore(1);
    final Duration timeout = Duration.ofSeconds(15);

    driver.addSyslogMessagesListener((msg) -> messageSemaphore.release());
    driver.addSyslogConnectionListener(() -> System.out.println("Connected to the web socket"));
    driver.addSyslogDisconnectionListener(() -> System.out.println("Disconnected from the web socket"));
    driver.addSyslogErrorsListener(Throwable::printStackTrace);
    try {
        driver.startSyslogBroadcast();
        messageSemaphore.acquire();
        // This is needed for pushing some internal log messages
        driver.runAppInBackground(Duration.ofSeconds(1));
        assertTrue(String.format("Didn't receive any log message after %s timeout",
                DurationFormatUtils.formatDuration(timeout.toMillis(), "H:mm:ss", true)),
                messageSemaphore.tryAcquire(timeout.toMillis(), TimeUnit.MILLISECONDS));
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    } finally {
        messageSemaphore.release();
        driver.stopSyslogBroadcast();
    }
}
 
Example 6
Source File: AWTTaskTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testWaitForItself() {
    final Semaphore s = new Semaphore(0);
    class R implements Runnable {
        int cnt;
        volatile Task waitFor;

        @Override
        public void run() {
            cnt++;
            try {
                s.acquire(); // Ensure waitFor != null.
            } catch (InterruptedException ex) {
                Exceptions.printStackTrace(ex);
            }
            waitFor.waitFinished();
        }
    }
    
    R r = new R();
    r.waitFor = new AWTTask(r, null);
    s.release();
    r.waitFor.waitFinished();
    
    assertEquals("Executed once", 1, r.cnt);
}
 
Example 7
Source File: Util.java    From Phlux with MIT License 5 votes vote down vote up
public static void acquire(Semaphore semaphore) {
    try {
        semaphore.acquire();
    }
    catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: SwingBrowserTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testDeadlockWithDebug() throws Exception {
    System.out.println("testDeadlockWithDebug");
    // simulates 71450 - without this special property it fails but that's why we debug with this property set
    String oldPropValue = System.getProperty("org.openide.awt.SwingBrowserImpl.do-not-block-awt");
    System.setProperty("org.openide.awt.SwingBrowserImpl.do-not-block-awt", "true");
    
    final HtmlBrowser.Impl impl = new SwingBrowserImpl();
    final JFrame f = new JFrame();
    final Semaphore s = new Semaphore(1);
    final URL url = new URL("test", "localhost", -1, "simple", new MyStreamHandler(s, null));
    
    s.acquire();
    SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
            Component comp = impl.getComponent();
            f.add(comp);
            f.setVisible(true);
            impl.setURL(url);
        }
    });
    System.out.println("browser visible, URL set");
    // now the browser is waiting for input stream
    
    // when failing it waits for Semaphore s but this is almost the same 
    // as waiting for reading from socket
    SwingUtilities.invokeAndWait(new Runnable() {
        public void run() {
            impl.reloadDocument();
        }
    });
    System.out.println("reload called");
    s.release();
    System.setProperty("org.openide.awt.SwingBrowserImpl.do-not-block-awt", (oldPropValue != null)? oldPropValue: "false");
    
    waitForLoading(url, f, impl);
}
 
Example 9
Source File: ControllerImplTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Test
public void testParallelCreateStream() throws Exception {
    final ExecutorService executorService = ExecutorServiceHelpers.newScheduledThreadPool(10, "testParallelCreateStream");
    Semaphore createCount = new Semaphore(-19);
    AtomicBoolean success = new AtomicBoolean(true);
    for (int i = 0; i < 10; i++) {
        executorService.submit(() -> {
            for (int j = 0; j < 2; j++) {
                try {
                    CompletableFuture<Boolean> createStreamStatus;
                    createStreamStatus = controllerClient.createStream("scope1", "streamparallel",
                            StreamConfiguration.builder()
                                    .scalingPolicy(ScalingPolicy.fixed(1))
                                    .build());
                    log.info("{}", createStreamStatus.get());
                    assertTrue(createStreamStatus.get());
                    createCount.release();
                } catch (Exception e) {
                    log.error("Exception when creating stream: {}", e);

                    // Don't wait for other threads to complete.
                    success.set(false);
                    createCount.release(20);
                }
            }
        });
    }
    createCount.acquire();
    ExecutorServiceHelpers.shutdown(executorService);
    assertTrue(success.get());
}
 
Example 10
Source File: AwexTest.java    From awex with Apache License 2.0 5 votes vote down vote up
@Test(timeout = 1000)
public void shouldExecuteAsRealTimeWhenWorkQueueHasQueuedTasks() throws Exception {
    setUpAwex();

    final Semaphore semaphore = new Semaphore(0);
    VoidTask someWaitingTask = new VoidTask() {
        @Override
        protected void runWithoutResult() throws InterruptedException {
            semaphore.acquire();
        }
    };

    VoidTask realTimeTask = new VoidTask(Task.PRIORITY_REAL_TIME) {
        @Override
        protected void runWithoutResult() throws InterruptedException {

        }
    };

    Promise<Void, Void> waitingPromise = mAwex.submit(someWaitingTask);
    mAwex.submit(new VoidTask() {
        @Override
        protected void runWithoutResult() throws InterruptedException {

        }
    });
    Promise<Void, Void> realTimePromise = mAwex.submit(realTimeTask);

    realTimePromise.getResult();

    semaphore.release();
    waitingPromise.getResult();
}
 
Example 11
Source File: UserService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private User getCached(CloudbreakUser cloudbreakUser) throws InterruptedException {
    Semaphore semaphore = UNDER_OPERATION.computeIfAbsent(cloudbreakUser, iu -> new Semaphore(1));
    semaphore.acquire();
    try {
        return cachedUserService.getUser(
                cloudbreakUser,
                this::findUserAndSetCrnIfExists,
                this::createUser);
    } finally {
        semaphore.release();
        UNDER_OPERATION.remove(cloudbreakUser);
    }
}
 
Example 12
Source File: BulkheadTest.java    From smallrye-fault-tolerance with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldLetMaxPlus1After1Left() throws Exception {
    Barrier delayBarrier = Barrier.noninterruptible();
    Semaphore letOneInSemaphore = new Semaphore(1);
    Semaphore finishedThreadsCount = new Semaphore(0);
    List<TestThread<String>> finishedThreads = new Vector<>();

    TestInvocation<String> invocation = TestInvocation.delayed(delayBarrier, () -> {
        letOneInSemaphore.acquire();
        // noinspection unchecked
        finishedThreads.add((TestThread<String>) Thread.currentThread());
        finishedThreadsCount.release();
        return "shouldLetMaxPlus1After1Left";
    });

    SemaphoreBulkhead<String> bulkhead = new SemaphoreBulkhead<>(invocation, "shouldLetMaxPlus1After1Left", 5, null);

    for (int i = 0; i < 5; i++) {
        runOnTestThread(bulkhead);
    }

    delayBarrier.open();
    finishedThreadsCount.acquire();
    assertThat(finishedThreads.get(0).await()).isEqualTo("shouldLetMaxPlus1After1Left");

    runOnTestThread(bulkhead);

    letOneInSemaphore.release(5);
    for (int i = 1; i < 6; i++) {
        finishedThreadsCount.acquire();
        assertThat(finishedThreads.get(i).await()).isEqualTo("shouldLetMaxPlus1After1Left");
    }
}
 
Example 13
Source File: RTMPMinaProtocolDecoder.java    From red5-server-common with Apache License 2.0 4 votes vote down vote up
/** {@inheritDoc} */
public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws ProtocolCodecException {
    // get the connection from the session
    String sessionId = (String) session.getAttribute(RTMPConnection.RTMP_SESSION_ID);
    log.trace("Session id: {}", sessionId);
    // connection verification routine
    @SuppressWarnings("unchecked")
    IConnectionManager<RTMPConnection> connManager = (IConnectionManager<RTMPConnection>) ((WeakReference<?>) session.getAttribute(RTMPConnection.RTMP_CONN_MANAGER)).get();
    RTMPConnection conn = (RTMPConnection) connManager.getConnectionBySessionId(sessionId);
    RTMPConnection connLocal = (RTMPConnection) Red5.getConnectionLocal();
    if (connLocal == null || !conn.getSessionId().equals(connLocal.getSessionId())) {
        if (log.isDebugEnabled() && connLocal != null) {
            log.debug("Connection local didn't match session");
        }
    }
    if (conn != null) {
        // set the connection to local if its referred to by this session
        Red5.setConnectionLocal(conn);
        // copy data range from incoming
        if (log.isTraceEnabled()) {
            log.trace("Incoming: in.position {}, in.limit {}, in.remaining {}", new Object[] { in.position(), in.limit(), in.remaining() });
        }
        byte[] arr = new byte[in.remaining()];
        in.get(arr);
        // create a buffer and store it on the session
        IoBuffer buf = (IoBuffer) session.getAttribute("buffer");
        if (buf == null) {
            buf = IoBuffer.allocate(arr.length);
            buf.setAutoExpand(true);
            session.setAttribute("buffer", buf);
        }
        // copy incoming into buffer
        buf.put(arr);
        // flip so we can read
        buf.flip();
        if (log.isTraceEnabled()) {
            //log.trace("Buffer before: {}", Hex.encodeHexString(arr));
            log.trace("Buffers info before: buf.position {}, buf.limit {}, buf.remaining {}", new Object[] { buf.position(), buf.limit(), buf.remaining() });
        }
        // get the connections decoder lock
        final Semaphore lock = conn.getDecoderLock();
        try {
            // acquire the decoder lock
            lock.acquire();
            // construct any objects from the decoded bugger
            List<?> objects = decoder.decodeBuffer(conn, buf);
            log.trace("Decoded: {}", objects);
            if (objects != null) {
                int writeCount = 0;
                for (Object object : objects) {
                    out.write(object);
                    writeCount++;
                }
                log.trace("Wrote {} objects", writeCount);
            }
        } catch (Exception e) {
            log.error("Error during decode", e);
        } finally {
            lock.release();
            // clear local
            Red5.setConnectionLocal(null);
        }
        if (log.isTraceEnabled()) {
            //log.trace("Buffer after: {}", Hex.encodeHexString(Arrays.copyOfRange(buf.array(), buf.position(), buf.limit())));
            log.trace("Buffers info after: buf.position {}, buf.limit {}, buf.remaining {}", new Object[] { buf.position(), buf.limit(), buf.remaining() });
        }
    } else {
        log.debug("Closing and skipping decode for unregistered connection: {}", sessionId);
        session.closeNow();
        log.debug("Session closing: {} reading: {} writing: {}", session.isClosing(), session.isReadSuspended(), session.isWriteSuspended());
    }
}
 
Example 14
Source File: BaseTest.java    From SweetBlue with GNU General Public License v3.0 4 votes vote down vote up
public void reacquire() throws Exception
{
    s = new Semaphore(0);
    s.acquire();
}
 
Example 15
Source File: StressAllocationGCEvents.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
public void run(String[] args) throws Exception {
    threadsCompleted = new Semaphore(0);
    System.out.println("Total memory= " + Runtime.getRuntime().maxMemory() + " bytes");

    int obj_size = DEFAULT_OBJ_SIZE;
    if (args.length > 0) {
        obj_size = Integer.parseInt(args[0]);
    }

    System.out.println("Objects size= " + obj_size + " bytes");
    ExecutorService executor
            = Executors.newFixedThreadPool(THREAD_COUNT, new NamedThreadFactory());
    Recording r = new Recording();
    r.enable(EVENT_NAME_ALLOCATION_REQUIRING_GC);
    r.start();

    System.out.println("Starting " + THREAD_COUNT + " threads");

    for (int i = 0; i < THREAD_COUNT; i++) {
        executor.execute(new Runner(obj_size));
    }

    // Wait for all threads to complete
    threadsCompleted.acquire(THREAD_COUNT);
    executor.shutdownNow();

    if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
        System.err.println("Thread pool did not terminate after 10 seconds after shutdown");
    }

    r.stop();

    List<RecordedEvent> allocationEvents
            = Events.fromRecording(r);

    System.out.println(EVENT_NAME_ALLOCATION_REQUIRING_GC + " " + allocationEvents.size());

    Events.hasEvents(allocationEvents);

    // check stacktrace depth
    for (RecordedEvent event : allocationEvents) {
        checkEvent(event);
    }
}
 
Example 16
Source File: Canvas4.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
private void thread_main()
{
    final Semaphore done = new Semaphore(0);
    int to_refresh = 1;
    try
    {
        final BufferedImage buf = new BufferedImage((int)canvas.getWidth(), (int)canvas.getHeight(), BufferedImage.TYPE_INT_RGB);
        final WritableImage image = new WritableImage((int)canvas.getWidth(), (int)canvas.getHeight());
        while (true)
        {
            // Prepare AWT image
            long start = System.currentTimeMillis();
            DemoHelper.refresh(buf);
            long ms = System.currentTimeMillis() - start;
            if (draw_ms < 0)
                draw_ms = ms;
            else
                draw_ms = (draw_ms * 9 + ms) / 10;

            counter.incrementAndGet();

            // Draw into Canvas on UI thread
            start = System.currentTimeMillis();
            Platform.runLater(() ->
            {
            	SwingFXUtils.toFXImage(buf, image);
                canvas.getGraphicsContext2D().drawImage(image, 0, 0);
                updates.setText(Long.toString(counter.get()));
                done.release();
            });

            // Wait for UI thread
            done.acquire();
            ms = System.currentTimeMillis() - start;
            if (update_ms < 0)
                update_ms = ms;
            else
                update_ms = (update_ms * 9 + ms) / 10;

            to_refresh = 1 - to_refresh;
            Thread.sleep(20);

            if ((counter.get() % 50) == 0)
            {
                System.out.println("Drawing: " + draw_ms + " ms");
                System.out.println("Update : " + update_ms + " ms");
            }
        }
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}
 
Example 17
Source File: DistributedQueue.java    From curator with Apache License 2.0 4 votes vote down vote up
private void processChildren(List<String> children, long currentVersion) throws Exception
{
    final Semaphore processedLatch = new Semaphore(0);
    final boolean   isUsingLockSafety = (lockPath != null);
    int             min = minItemsBeforeRefresh;
    for ( final String itemNode : children )
    {
        if ( Thread.currentThread().isInterrupted() )
        {
            processedLatch.release(children.size());
            break;
        }

        if ( !itemNode.startsWith(QUEUE_ITEM_NAME) )
        {
            log.warn("Foreign node in queue path: " + itemNode);
            processedLatch.release();
            continue;
        }

        if ( min-- <= 0 )
        {
            if ( refreshOnWatch && (currentVersion != childrenCache.getData().version) )
            {
                processedLatch.release(children.size());
                break;
            }
        }

        if ( getDelay(itemNode) > 0 )
        {
            processedLatch.release();
            continue;
        }

        executor.execute
        (
            new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        if ( isUsingLockSafety )
                        {
                            processWithLockSafety(itemNode, ProcessType.NORMAL);
                        }
                        else
                        {
                            processNormally(itemNode, ProcessType.NORMAL);
                        }
                    }
                    catch ( Exception e )
                    {
                        ThreadUtils.checkInterrupted(e);
                        log.error("Error processing message at " + itemNode, e);
                    }
                    finally
                    {
                        processedLatch.release();
                    }
                }
            }
        );
    }

    processedLatch.acquire(children.size());
}
 
Example 18
Source File: ZookeeperDeployer.java    From ankush with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Undeploy nodes.
 * 
 * @param clusterConfig
 *            the cluster config
 * @return true, if successful
 */
private boolean undeployNodes(ClusterConfig clusterConfig) {
	logger.info("Undeploying Zookeeper...", this.componentName);
	ComponentConfig compConfig = clusterConfig.getComponents().get(
			this.componentName);
	final Semaphore semaphore = new Semaphore(compConfig.getNodes().size());

	boolean status = false;
	try {
		for (final String host : compConfig.getNodes().keySet()) {
			// acuiring the semaphore
			semaphore.acquire();
			final NodeConfig nodeConfig = clusterConfig.getNodes()
					.get(host);
			final ZookeeperWorker zookeeperWorker = new ZookeeperWorker(
					this.clusterConfig, this.componentName, nodeConfig);
			final ZookeeperServiceMonitor zooServiceMonitor = new ZookeeperServiceMonitor(
					clusterConfig, this.componentName);
			// zooServiceMonitor.setCluster(clusterConfig,
			// this.componentName);
			AppStoreWrapper.getExecutor().execute(new Runnable() {
				@Override
				public void run() {
					// logger.info("Stopping Zookeeper...", componentName);
					// zookeeperWorker.action(ZookeeperConstant.Action.STOP);
					zooServiceMonitor.action(ZookeeperConstant.Action.STOP,
							nodeConfig.getHost());
					logger.info("removing Zookeeper...", componentName);
					zookeeperWorker.removeNode();
					if (semaphore != null) {
						semaphore.release();
					}
				}
			});
		}
		// waiting for all semaphores to finish the installation.
		semaphore.acquire(compConfig.getNodes().size());
		status = AnkushUtils.getStatus(clusterConfig, compConfig.getNodes()
				.keySet());
	} catch (Exception e) {
		logger.error(e.getMessage(), this.componentName, e);
	}
	if (status) {
		logger.info("Undeploying Zookeeper is over.", componentName);
	} else {
		logger.error("Undeploying Zookeeper failed.", componentName);
		clusterConfig.addError(getComponentName(),
				"Undeploying Zookeeper failed.");
	}
	return status;
}
 
Example 19
Source File: BleScanTest.java    From SweetBlue with GNU General Public License v3.0 4 votes vote down vote up
@Test(timeout = 30000)
public void testInfiniteScanMain() throws Exception
{
    final Semaphore finishedSemaphore = new Semaphore(0);

    final AtomicBoolean started = new AtomicBoolean(false);

    mgr.m_config.runOnMainThread = true;
    mgr.m_config.updateLoopCallback = new PI_UpdateLoop.Callback()
    {
        @Override public void onUpdate(double timestep_seconds)
        {
            if (started.get())
            {
                assertTrue("BleManager is not SCANNING!", mgr.is(BleManagerState.SCANNING));
                if (mgr.getTimeInState(BleManagerState.SCANNING).secs() >= 20.0)
                {
                    shutdown(finishedSemaphore);
                }
            }
        }
    };
    mgr.setConfig(mgr.m_config);

    mgr.setListener_State(new ManagerStateListener()
    {
        @Override public void onEvent(BleManager.StateListener.StateEvent e)
        {
            if (e.didEnter(BleManagerState.SCANNING))
            {
                started.set(true);
            }
        }
    });

    checkState();

    mgr.startScan();

    finishedSemaphore.acquire();
}
 
Example 20
Source File: ServerCallsTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void inprocessTransportManualFlow() throws Exception {
  final Semaphore semaphore = new Semaphore(1);
  ServerServiceDefinition service = ServerServiceDefinition.builder(
      new ServiceDescriptor("some", STREAMING_METHOD))
      .addMethod(STREAMING_METHOD, ServerCalls.asyncBidiStreamingCall(
          new ServerCalls.BidiStreamingMethod<Integer, Integer>() {
            int iteration;

            @Override
            public StreamObserver<Integer> invoke(StreamObserver<Integer> responseObserver) {
              final ServerCallStreamObserver<Integer> serverCallObserver =
                  (ServerCallStreamObserver<Integer>) responseObserver;
              serverCallObserver.setOnReadyHandler(new Runnable() {
                @Override
                public void run() {
                  while (serverCallObserver.isReady()) {
                    serverCallObserver.onNext(iteration);
                  }
                  iteration++;
                  semaphore.release();
                }
              });
              return new ServerCalls.NoopStreamObserver<Integer>() {
                @Override
                public void onCompleted() {
                  serverCallObserver.onCompleted();
                }
              };
            }
          }))
      .build();
  long tag = System.nanoTime();
  InProcessServerBuilder.forName("go-with-the-flow" + tag).addService(service).build().start();
  ManagedChannel channel = InProcessChannelBuilder.forName("go-with-the-flow" + tag).build();
  final ClientCall<Integer, Integer> clientCall = channel.newCall(STREAMING_METHOD,
      CallOptions.DEFAULT);
  final CountDownLatch latch = new CountDownLatch(1);
  final int[] receivedMessages = new int[6];
  clientCall.start(new ClientCall.Listener<Integer>() {
    int index;

    @Override
    public void onMessage(Integer message) {
      receivedMessages[index++] = message;
    }

    @Override
    public void onClose(Status status, Metadata trailers) {
      latch.countDown();
    }
  }, new Metadata());
  semaphore.acquire();
  clientCall.request(1);
  semaphore.acquire();
  clientCall.request(2);
  semaphore.acquire();
  clientCall.request(3);
  clientCall.halfClose();
  latch.await(5, TimeUnit.SECONDS);
  // Very that number of messages produced in each onReady handler call matches the number
  // requested by the client.
  assertArrayEquals(new int[]{0, 1, 1, 2, 2, 2}, receivedMessages);
}