### Question:
LimitingConnectionFactoryFilter implements ConnectionFactoryFilter<ResolvedAddress, C> { public static <A, C extends ListenableAsyncCloseable> ConnectionFactoryFilter<A, C> withMax( int maxConnections) { return new LimitingConnectionFactoryFilter<>(new MaxConnectionsLimiter<>(maxConnections)); } private  LimitingConnectionFactoryFilter(final ConnectionLimiter<ResolvedAddress, C> limiter); static ConnectionFactoryFilter<A, C> withMax(
            int maxConnections); static ConnectionFactoryFilter<A, C> with(
            ConnectionLimiter<A, C> limiter); @Override ConnectionFactory<ResolvedAddress, C> create(final ConnectionFactory<ResolvedAddress, C> original);  }### Answer:
@Test public void enforceMaxConnections() throws Exception { ConnectionFactory<String, ? extends ListenableAsyncCloseable> cf = makeCF(LimitingConnectionFactoryFilter.withMax(1), original); cf.newConnection("c1", null).toFuture().get(); expectedException.expect(ExecutionException.class); expectedException.expectCause(instanceOf(ConnectException.class)); cf.newConnection("c2", null).toFuture().get(); }
@Test public void onCloseReleasesPermit() throws Exception { ConnectionFactory<String, ? extends ListenableAsyncCloseable> cf = makeCF(LimitingConnectionFactoryFilter.withMax(1), original); cf.newConnection("c1", null).toFuture().get(); connectAndVerifyFailed(cf); connectionOnClose.take().onComplete(); cf.newConnection("c3", null).toFuture().get(); }
@Test public void cancelReleasesPermit() throws Exception { ConnectionFactory<String, ListenableAsyncCloseable> o = newMockConnectionFactory(); when(o.newConnection(any(), any())).thenReturn(never()); ConnectionFactory<String, ? extends ListenableAsyncCloseable> cf = makeCF(LimitingConnectionFactoryFilter.withMax(1), o); connectlistener.listen(cf.newConnection("c1", null)).verifyNoEmissions(); connectAndVerifyFailed(cf); connectlistener.cancel(); ListenableAsyncCloseable c = mock(ListenableAsyncCloseable.class); when(c.onClose()).thenReturn(Completable.never()); when(o.newConnection(any(), any())).thenReturn(succeeded(c)); cf.newConnection("c2", null).toFuture().get(); }