RefreshingManagedChannel extends ManagedChannel { @Override public <ReqT, RespT> ClientCall<ReqT, RespT> newCall( MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions) { lock.readLock().lock(); try { return delegate.newCall(methodDescriptor, callOptions); } finally { lock.readLock().unlock(); } } RefreshingManagedChannel(
      ChannelFactory channelFactory, ScheduledExecutorService scheduledExecutorService); @Override ClientCall<ReqT, RespT> newCall(
      MethodDescriptor<ReqT, RespT> methodDescriptor, CallOptions callOptions); @Override String authority(); @Override ManagedChannel shutdown(); @Override ManagedChannel shutdownNow(); @Override boolean isShutdown(); @Override boolean isTerminated(); @Override boolean awaitTermination(long timeout, TimeUnit unit);  }
@Test public void channelRefreshShouldSwapChannels() throws IOException { ManagedChannel underlyingChannel1 = Mockito.mock(ManagedChannel.class); ManagedChannel underlyingChannel2 = Mockito.mock(ManagedChannel.class); ScheduledExecutorService scheduledExecutorService = Mockito.mock(ScheduledExecutorService.class); final List<Runnable> channelRefreshers = new ArrayList<>(); Answer extractChannelRefresher = new Answer() { public Object answer(InvocationOnMock invocation) { channelRefreshers.add((Runnable) invocation.getArgument(0)); return null; } }; Mockito.doAnswer(extractChannelRefresher) .when(scheduledExecutorService) .schedule( Mockito.any(Runnable.class), Mockito.anyLong(), Mockito.eq(TimeUnit.MILLISECONDS)); FakeChannelFactory channelFactory = new FakeChannelFactory(Arrays.asList(underlyingChannel1, underlyingChannel2)); ManagedChannel refreshingManagedChannel = new RefreshingManagedChannel(channelFactory, scheduledExecutorService); refreshingManagedChannel.newCall( FakeMethodDescriptor.<String, Integer>create(), CallOptions.DEFAULT); Mockito.verify(underlyingChannel1, Mockito.only()) .newCall(Mockito.<MethodDescriptor<String, Integer>>any(), Mockito.any(CallOptions.class)); channelRefreshers.get(0).run(); refreshingManagedChannel.newCall( FakeMethodDescriptor.<String, Integer>create(), CallOptions.DEFAULT); Mockito.verify(underlyingChannel2, Mockito.only()) .newCall(Mockito.<MethodDescriptor<String, Integer>>any(), Mockito.any(CallOptions.class)); }