Java Code Examples for io.grpc.ManagedChannel#awaitTermination()
The following examples show how to use
io.grpc.ManagedChannel#awaitTermination() .
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: HelloWorldAltsClient.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
private void run(String[] args) throws InterruptedException { parseArgs(args); ExecutorService executor = Executors.newFixedThreadPool(1); ManagedChannel channel = AltsChannelBuilder.forTarget(serverAddress).executor(executor).build(); try { GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel); HelloReply resp = stub.sayHello(HelloRequest.newBuilder().setName("Waldo").build()); logger.log(Level.INFO, "Got {0}", resp); } finally { channel.shutdown(); channel.awaitTermination(1, TimeUnit.SECONDS); // Wait until the channel has terminated, since tasks can be queued after the channel is // shutdown. executor.shutdown(); } }
Example 2
Source File: ManagedChannelUtils.java From pinpoint with Apache License 2.0 | 6 votes |
public static boolean shutdownManagedChannel(String name, ManagedChannel managedChannel, long timeout, TimeUnit unit) { if (managedChannel == null) { return false; } logger.debug("shutdown {}", name); managedChannel.shutdown(); try { final boolean success = managedChannel.awaitTermination(timeout, unit); if (!success) { logger.warn("shutdown timeout {}", name); } return success; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; } }
Example 3
Source File: HelloWorldAltsClient.java From grpc-java with Apache License 2.0 | 6 votes |
private void run(String[] args) throws InterruptedException { parseArgs(args); ExecutorService executor = Executors.newFixedThreadPool(1); ManagedChannel channel = AltsChannelBuilder.forTarget(serverAddress).executor(executor).build(); try { GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel); HelloReply resp = stub.sayHello(HelloRequest.newBuilder().setName("Waldo").build()); logger.log(Level.INFO, "Got {0}", resp); } finally { channel.shutdown(); channel.awaitTermination(1, TimeUnit.SECONDS); // Wait until the channel has terminated, since tasks can be queued after the channel is // shutdown. executor.shutdown(); } }
Example 4
Source File: ManagedChannelHelper.java From sofa-jraft with Apache License 2.0 | 5 votes |
/** * The following method shuts down an {@code ManagedChannel} in two * phases, first by calling {@code shutdown} to reject incoming tasks, * and then calling {@code shutdownNow}, if necessary, to cancel any * lingering tasks. */ public static boolean shutdownAndAwaitTermination(final ManagedChannel mChannel, final long timeoutMillis) { if (mChannel == null) { return true; } // disable new tasks from being submitted mChannel.shutdown(); final TimeUnit unit = TimeUnit.MILLISECONDS; final long phaseOne = timeoutMillis / 5; try { // wait a while for existing tasks to terminate if (mChannel.awaitTermination(phaseOne, unit)) { return true; } mChannel.shutdownNow(); // wait a while for tasks to respond to being cancelled if (mChannel.awaitTermination(timeoutMillis - phaseOne, unit)) { return true; } LOG.warn("Fail to shutdown managed channel: {}.", mChannel); } catch (final InterruptedException e) { // (Re-)cancel if current thread also interrupted mChannel.shutdownNow(); // preserve interrupt status Thread.currentThread().interrupt(); } return false; }
Example 5
Source File: CompletableFutureEndToEndTest.java From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void serverRunsAndRespondsCorrectly() throws ExecutionException, IOException, InterruptedException, TimeoutException { final String name = UUID.randomUUID().toString(); Server server = ServerBuilder.forPort(9999) .addService(new GreeterImpl()) .build(); server.start(); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", server.getPort()) .usePlaintext(true) .build(); GreeterGrpc8.GreeterCompletableFutureStub stub = GreeterGrpc8.newCompletableFutureStub(channel); CompletableFuture<HelloResponse> response = stub.sayHello(HelloRequest.newBuilder().setName(name).build()); await().atMost(3, TimeUnit.SECONDS).until(() -> response.isDone() && response.get().getMessage().contains(name)); channel.shutdown(); channel.awaitTermination(1, TimeUnit.MINUTES); channel.shutdownNow(); server.shutdown(); server.awaitTermination(1, TimeUnit.MINUTES); server.shutdownNow(); }
Example 6
Source File: Executor.java From bazel-buildfarm with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { String host = args[0]; String instanceName = args[1]; String blobsDir; if (args.length == 3) { blobsDir = args[2]; } else { blobsDir = null; } Scanner scanner = new Scanner(System.in); ImmutableList.Builder<Digest> actionDigests = ImmutableList.builder(); while (scanner.hasNext()) { actionDigests.add(DigestUtil.parseDigest(scanner.nextLine())); } ManagedChannel channel = createChannel(host); if (blobsDir != null) { System.out.println("Loading blobs into cas"); loadFilesIntoCAS(instanceName, channel, Paths.get(blobsDir)); } ExecutionStub execStub = ExecutionGrpc.newStub(channel); executeActions(instanceName, actionDigests.build(), execStub); channel.shutdown(); channel.awaitTermination(1, SECONDS); }
Example 7
Source File: Utils.java From dropwizard-grpc with Apache License 2.0 | 5 votes |
/** * Shuts down the given channel if not <code>null</code>, waiting for up to 1 second. * * @param channel the channel to shut down */ public static void shutdownChannel(final ManagedChannel channel) { if (channel != null) { channel.shutdown(); try { channel.awaitTermination(1, TimeUnit.SECONDS); } catch (final InterruptedException e) { // silently swallow exception } } }
Example 8
Source File: GrpcRemoteExecutionClients.java From buck with Apache License 2.0 | 5 votes |
private static void closeChannel(ManagedChannel channel) { channel.shutdown(); try { channel.awaitTermination(3, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } }
Example 9
Source File: BaseITTracingClientInterceptor.java From brave with Apache License 2.0 | 5 votes |
void closeClient(ManagedChannel client) { client.shutdown(); try { client.awaitTermination(1, TimeUnit.SECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError(e); } }
Example 10
Source File: ChatClient.java From reactive-grpc with BSD 3-Clause "New" or "Revised" License | 4 votes |
public static void main(String[] args) throws Exception { String author = args.length == 0 ? "Random_Stranger" : args[0]; // Connect to the sever ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", PORT).usePlaintext().build(); RxChatGrpc.RxChatStub stub = RxChatGrpc.newRxStub(channel); CountDownLatch done = new CountDownLatch(1); ConsoleReader console = new ConsoleReader(); console.println("Type /quit to exit"); /* ****************************** * Subscribe to incoming messages * ******************************/ disposables.add(Single.just(Empty.getDefaultInstance()) .as(stub::getMessages) .filter(message -> !message.getAuthor().equals(author)) .subscribe(message -> printLine(console, message.getAuthor(), message.getMessage()))); /* ************************* * Publish outgoing messages * *************************/ disposables.add(Observable // Send connection message .just(author + " joined.") // Send user input .concatWith(Observable.fromIterable(new ConsoleIterator(console, author + " > "))) // Send disconnect message .concatWith(Single.just(author + " left.")) .map(msg -> toMessage(author, msg)) .flatMapSingle(stub::postMessage) .subscribe( ChatClient::doNothing, throwable -> printLine(console, "ERROR", throwable.getMessage()), done::countDown )); // Wait for a signal to exit, then clean up done.await(); disposables.dispose(); channel.shutdown(); channel.awaitTermination(1, TimeUnit.SECONDS); console.getTerminal().restore(); }
Example 11
Source File: ReactorChatClient.java From reactive-grpc with BSD 3-Clause "New" or "Revised" License | 4 votes |
public static void main(String[] args) throws Exception { // Connect to the sever ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", PORT).usePlaintext().build(); ReactorChatGrpc.ReactorChatStub stub = ReactorChatGrpc.newReactorStub(channel); CountDownLatch done = new CountDownLatch(1); ConsoleReader console = new ConsoleReader(); // Prompt the user for their name console.println("Press ctrl+D to quit"); String author = console.readLine("Who are you? > "); stub.postMessage(toMessage(author, author + " joined.")).subscribe(); // Subscribe to incoming messages Disposable chatSubscription = stub.getMessages(Mono.just(Empty.getDefaultInstance())).subscribe( message -> { // Don't re-print our own messages if (!message.getAuthor().equals(author)) { printLine(console, message.getAuthor(), message.getMessage()); } }, throwable -> { printLine(console, "ERROR", throwable.getMessage()); done.countDown(); }, done::countDown ); // Publish outgoing messages Flux.fromIterable(new ConsoleIterator(console, author + " > ")) .map(msg -> toMessage(author, msg)) .flatMap(stub::postMessage) .subscribe( empty -> { }, throwable -> { printLine(console, "ERROR", throwable.getMessage()); done.countDown(); }, done::countDown ); // Wait for a signal to exit, then clean up done.await(); stub.postMessage(toMessage(author, author + " left.")).subscribe(); chatSubscription.dispose(); channel.shutdown(); channel.awaitTermination(1, TimeUnit.SECONDS); console.getTerminal().restore(); }
Example 12
Source File: ChannelFactoryTest.java From pinpoint with Apache License 2.0 | 4 votes |
@Test public void build() throws InterruptedException { HeaderFactory headerFactory = new AgentHeaderFactory("agentId", "appName", System.currentTimeMillis()); CountRecordClientInterceptor countRecordClientInterceptor = new CountRecordClientInterceptor(); ChannelFactoryBuilder channelFactoryBuilder = new DefaultChannelFactoryBuilder(this.getClass().getSimpleName()); channelFactoryBuilder.setHeaderFactory(headerFactory); channelFactoryBuilder.setNameResolverProvider(nameResolverProvider); channelFactoryBuilder.addClientInterceptor(countRecordClientInterceptor); channelFactoryBuilder.setClientOption(new ClientOption.Builder().build()); ChannelFactory channelFactory = channelFactoryBuilder.build(); ManagedChannel managedChannel = channelFactory.build("127.0.0.1", PORT); managedChannel.getState(false); SpanGrpc.SpanStub spanStub = SpanGrpc.newStub(managedChannel); final QueueingStreamObserver<Empty> responseObserver = new QueueingStreamObserver<Empty>(); logger.debug("sendSpan"); StreamObserver<PSpanMessage> sendSpan = spanStub.sendSpan(responseObserver); PSpan pSpan = newSpan(); PSpanMessage message = PSpanMessage.newBuilder().setSpan(pSpan).build(); logger.debug("client-onNext"); sendSpan.onNext(message); logger.debug("wait for response"); Empty value = responseObserver.getValue(); logger.debug("response:{}", value); logger.debug("client-onCompleted"); sendSpan.onCompleted(); Assert.assertTrue(countRecordClientInterceptor.getExecutedInterceptCallCount() == 1); logger.debug("state:{}", managedChannel.getState(true)); spanService.awaitOnCompleted(); logger.debug("managedChannel shutdown"); managedChannel.shutdown(); managedChannel.awaitTermination(1000, TimeUnit.MILLISECONDS); channelFactory.close(); }