Elffuss BraidHub

kikocis/java-driver public

JAVA-1371: Reintroduce connection pool timeout (#792)

Changeseta6025d8125efbd4d1083e3debf6c145445f83fb0f1b91fdf52d82d19ae7fadc2
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2017-02-01 15:12 -08:00
CommitterGitHub <noreply@github.com> · 2017-02-01 15:12 -08:00
Parents89b1172e93b0

Browse the files at this changeset

8 files changed

modified changelog/README.md +5 −0
@@ -1,5 +1,10 @@
11 ## Changelog
22
3+### 3.0.7 (in progress)
4+
5+- [bug] JAVA-1371: Reintroduce connection pool timeout.
6+
7+
38 ### 3.0.6
49
510 - [bug] JAVA-1330: Add un/register for SchemaChangeListener in DelegatingCluster
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +59 −18
@@ -24,6 +24,7 @@
2424 import com.google.common.base.Throwables;
2525 import com.google.common.collect.Lists;
2626 import com.google.common.util.concurrent.*;
27+import io.netty.util.concurrent.EventExecutor;
2728 import org.slf4j.Logger;
2829 import org.slf4j.LoggerFactory;
2930
@@ -57,14 +58,16 @@
5758 @VisibleForTesting
5859 final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
5960
60- private final Queue<SettableFuture<Connection>> pendingBorrows = new ConcurrentLinkedQueue<SettableFuture<Connection>>();
61+ private final Queue<PendingBorrow> pendingBorrows = new ConcurrentLinkedQueue<PendingBorrow>();
6162 private final AtomicInteger pendingBorrowCount = new AtomicInteger();
6263
6364 private final Runnable newConnectionTask;
6465
6566 private final AtomicInteger scheduledForCreation = new AtomicInteger();
6667
67- protected final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
68+ private final EventExecutor timeoutsExecutor;
69+
70+ private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
6871
6972 private enum Phase {INITIALIZING, READY, INIT_FAILED, CLOSING}
7073
@@ -93,6 +96,8 @@
9396 this.open = new AtomicInteger();
9497
9598 this.minAllowedStreams = options().getMaxRequestsPerConnection(hostDistance) * 3 / 4;
99+
100+ this.timeoutsExecutor = manager.getCluster().manager.connectionFactory.eventLoopGroup.next();
96101 }
97102
98103 /**
@@ -190,7 +195,7 @@
190195 return manager.configuration().getPoolingOptions();
191196 }
192197
193- ListenableFuture<Connection> borrowConnection(int maxQueueSize) {
198+ ListenableFuture<Connection> borrowConnection(long timeout, TimeUnit unit, int maxQueueSize) {
194199 Phase phase = this.phase.get();
195200 if (phase != Phase.READY)
196201 return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is " + phase));
@@ -207,7 +212,7 @@
207212 manager.blockingExecutor().submit(newConnectionTask);
208213 }
209214 }
210- return enqueue(maxQueueSize);
215+ return enqueue(timeout, unit, maxQueueSize);
211216 }
212217 }
213218
@@ -228,13 +233,13 @@
228233 // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between
229234 // the previous check to connections and now. But in that case, the line above will have trigger the creation of
230235 // a new connection, so just wait that connection and move on
231- return enqueue(maxQueueSize);
236+ return enqueue(timeout, unit, maxQueueSize);
232237 } else {
233238 while (true) {
234239 int inFlight = leastBusy.inFlight.get();
235240
236241 if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) {
237- return enqueue(maxQueueSize);
242+ return enqueue(timeout, unit, maxQueueSize);
238243 }
239244
240245 if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
@@ -264,8 +269,8 @@
264269 return leastBusy.setKeyspaceAsync(manager.poolsState.keyspace);
265270 }
266271
267- private ListenableFuture<Connection> enqueue(int maxQueueSize) {
268- if (maxQueueSize == 0) {
272+ private ListenableFuture<Connection> enqueue(long timeout, TimeUnit unit, int maxQueueSize) {
273+ if (timeout == 0 || maxQueueSize == 0) {
269274 return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), 0));
270275 }
271276
@@ -279,16 +284,16 @@
279284 }
280285 }
281286
282- SettableFuture<Connection> future = SettableFuture.create();
283- pendingBorrows.add(future);
287+ PendingBorrow pendingBorrow = new PendingBorrow(timeout, unit, timeoutsExecutor);
288+ pendingBorrows.add(pendingBorrow);
284289
285290 // If we raced with shutdown, make sure the future will be completed. This has no effect if it was properly
286291 // handled in closeAsync.
287292 if (phase.get() == Phase.CLOSING) {
288- future.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
293+ pendingBorrow.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
289294 }
290295
291- return future;
296+ return pendingBorrow.future;
292297 }
293298
294299 void returnConnection(Connection connection) {
@@ -316,7 +321,7 @@
316321 }
317322
318323 // When a connection gets returned to the pool, check if there are pending borrows that can be completed with it.
319- private void dequeue(Connection connection) {
324+ private void dequeue(final Connection connection) {
320325 while (!pendingBorrows.isEmpty()) {
321326
322327 // We can only reuse the connection if it's under its maximum number of inFlight requests.
@@ -333,21 +338,25 @@
333338 }
334339 }
335340
336- final SettableFuture<Connection> pendingBorrow = pendingBorrows.poll();
341+ final PendingBorrow pendingBorrow = pendingBorrows.poll();
337342 if (pendingBorrow == null) {
338343 // Another thread has emptied the queue since our last check, restore the count
339344 connection.inFlight.decrementAndGet();
340345 } else {
341- totalInFlight.incrementAndGet();
342346 pendingBorrowCount.decrementAndGet();
343347 // Ensure that the keyspace set on the connection is the one set on the pool state, in the general case it will be.
344348 ListenableFuture<Connection> setKeyspaceFuture = connection.setKeyspaceAsync(manager.poolsState.keyspace);
345349 // Slight optimization, if the keyspace was already correct the future will be complete, so simply complete it here.
346350 if (setKeyspaceFuture.isDone()) {
347351 try {
348- pendingBorrow.set(Uninterruptibles.getUninterruptibly(setKeyspaceFuture));
352+ if (pendingBorrow.set(Uninterruptibles.getUninterruptibly(setKeyspaceFuture))) {
353+ totalInFlight.incrementAndGet();
354+ } else {
355+ connection.inFlight.decrementAndGet();
356+ }
349357 } catch (ExecutionException e) {
350358 pendingBorrow.setException(e.getCause());
359+ connection.inFlight.decrementAndGet();
351360 }
352361 } else {
353362 // Otherwise the keyspace did need to be set, tie the pendingBorrow future to the set keyspace completion.
@@ -355,12 +364,17 @@
355364
356365 @Override
357366 public void onSuccess(Connection c) {
358- pendingBorrow.set(c);
367+ if (pendingBorrow.set(c)) {
368+ totalInFlight.incrementAndGet();
369+ } else {
370+ connection.inFlight.decrementAndGet();
371+ }
359372 }
360373
361374 @Override
362375 public void onFailure(Throwable t) {
363376 pendingBorrow.setException(t);
377+ connection.inFlight.decrementAndGet();
364378 }
365379 });
366380 }
@@ -592,7 +606,7 @@
592606
593607 phase.set(Phase.CLOSING);
594608
595- for (SettableFuture<Connection> pendingBorrow : pendingBorrows) {
609+ for (PendingBorrow pendingBorrow : pendingBorrows) {
596610 pendingBorrow.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
597611 }
598612
@@ -664,4 +678,31 @@
664678 this.keyspace = keyspace;
665679 }
666680 }
681+
682+ private class PendingBorrow {
683+ final SettableFuture<Connection> future;
684+ final Future<?> timeoutTask;
685+
686+ PendingBorrow(final long timeout, final TimeUnit unit, EventExecutor timeoutsExecutor) {
687+ this.future = SettableFuture.create();
688+ this.timeoutTask = timeoutsExecutor.schedule(new Runnable() {
689+ @Override
690+ public void run() {
691+ future.setException(
692+ new BusyPoolException(host.getSocketAddress(), timeout, unit));
693+ }
694+ }, timeout, unit);
695+ }
696+
697+ boolean set(Connection connection) {
698+ boolean succeeded = this.future.set(connection);
699+ this.timeoutTask.cancel(false);
700+ return succeeded;
701+ }
702+
703+ void setException(Throwable exception) {
704+ this.future.setException(exception);
705+ this.timeoutTask.cancel(false);
706+ }
707+ }
667708 }
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +39 −10
@@ -128,9 +128,8 @@
128128 public static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120;
129129
130130 /**
131- * @deprecated see {@link #setPoolTimeoutMillis(int)}
131+ * The default value for {@link #getPoolTimeoutMillis()} ({@value}).
132132 */
133- @Deprecated
134133 public static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
135134
136135 /**
@@ -157,6 +156,7 @@
157156 private volatile int maxRequestsPerConnectionRemote = UNSET;
158157
159158 private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
159+ private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
160160 private volatile int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE;
161161 private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
162162
@@ -406,19 +406,39 @@
406406 }
407407
408408 /**
409- * @deprecated see {@link #setPoolTimeoutMillis(int)}. This method always returns 0.
409+ * Returns the timeout when trying to acquire a connection from a host's pool.
410+ *
411+ * @return the timeout.
410412 */
411- @Deprecated
412413 public int getPoolTimeoutMillis() {
413- return 0;
414+ return poolTimeoutMillis;
414415 }
415416
416417 /**
417- * @deprecated the connection pool does not use a timeout anymore, incoming requests are now throttled with a
418- * threshold on the {@link #setMaxQueueSize(int) queue size}. This method has no effect.
418+ * Sets the timeout when trying to acquire a connection from a host's pool.
419+ * <p/>
420+ * This option works in concert with {@link #setMaxQueueSize(int)} to determine what happens if the driver tries
421+ * to borrow a connection from the pool but none is available:
422+ * <ul>
423+ * <li>if either option is set to zero, the attempt is rejected immediately;</li>
424+ * <li>else if more than {@code maxQueueSize} requests are already waiting for a connection, the attempt is also
425+ * rejected;</li>
426+ * <li>otherwise, the attempt is enqueued; if a connection becomes available before {@code poolTimeoutMillis}
427+ * has elapsed, then the attempt succeeds, otherwise it is rejected.</li>
428+ * </ul>
429+ * If the attempt is rejected, the driver will move to the next host in the
430+ * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#newQueryPlan(String, Statement)} query plan}.
431+ * <p/>
432+ * The default is 5 seconds. If this option is set to zero, the driver won't wait at all.
433+ *
434+ * @param poolTimeoutMillis the new value in milliseconds.
435+ * @return this {@code PoolingOptions}
436+ * @throws IllegalArgumentException if the timeout is negative.
419437 */
420- @Deprecated
421438 public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) {
439+ if (poolTimeoutMillis < 0)
440+ throw new IllegalArgumentException("Pool timeout must be positive");
441+ this.poolTimeoutMillis = poolTimeoutMillis;
422442 return this;
423443 }
424444
@@ -434,8 +454,17 @@
434454 /**
435455 * Sets the maximum number of requests that get enqueued if no connection is available.
436456 * <p/>
437- * If the queue grows past this value, new requests will be rejected immediately (and the driver will move to the
438- * next host in the query plan). This limit is per connection pool, not global to the driver.
457+ * This option works in concert with {@link #setPoolTimeoutMillis(int)} to determine what happens if the driver
458+ * tries to borrow a connection from the pool but none is available:
459+ * <ul>
460+ * <li>if either options is set to zero, the attempt is rejected immediately;</li>
461+ * <li>else if more than {@code maxQueueSize} requests are already waiting for a connection, the attempt is also
462+ * rejected;</li>
463+ * <li>otherwise, the attempt is enqueued; if a connection becomes available before {@code poolTimeoutMillis}
464+ * has elapsed, then the attempt succeeds, otherwise it is rejected.</li>
465+ * </ul>
466+ * If the attempt is rejected, the driver will move to the next host in the
467+ * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#newQueryPlan(String, Statement)} query plan}.
439468 * <p/>
440469 * The default value is {@value DEFAULT_MAX_QUEUE_SIZE}. If this option is set to zero, the driver will never
441470 * enqueue requests.
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +3 −1
@@ -289,8 +289,10 @@
289289 if (allowSpeculativeExecutions && nextExecutionScheduled.compareAndSet(false, true))
290290 scheduleExecution(speculativeExecutionPlan.nextExecution(host));
291291
292+ PoolingOptions poolingOptions = manager.configuration().getPoolingOptions();
292293 ListenableFuture<Connection> connectionFuture = pool.borrowConnection(
293- manager.configuration().getPoolingOptions().getMaxQueueSize());
294+ poolingOptions.getPoolTimeoutMillis(), TimeUnit.MILLISECONDS,
295+ poolingOptions.getMaxQueueSize());
294296 Futures.addCallback(connectionFuture, new FutureCallback<Connection>() {
295297 @Override
296298 public void onSuccess(Connection connection) {
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +2 −1
@@ -624,7 +624,8 @@
624624 try {
625625 // Preparing is not critical: if it fails, it will fix itself later when the user tries to execute
626626 // the prepared query. So don't wait if no connection is available, simply abort.
627- ListenableFuture<Connection> connectionFuture = entry.getValue().borrowConnection(0);
627+ ListenableFuture<Connection> connectionFuture = entry.getValue().borrowConnection(
628+ 0, TimeUnit.MILLISECONDS, 0);
628629 ListenableFuture<Response> prepareFuture = Futures.transform(connectionFuture,
629630 new AsyncFunction<Connection, Response>() {
630631 @Override
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyPoolException.java +15 −6
@@ -20,6 +20,7 @@
2020
2121 import java.net.InetAddress;
2222 import java.net.InetSocketAddress;
23+import java.util.concurrent.TimeUnit;
2324
2425 /**
2526 * Indicates that a connection pool has run out of available connections.
@@ -44,16 +45,18 @@
4445 private static final long serialVersionUID = 0;
4546
4647 private final InetSocketAddress address;
47- private final int queueSize;
4848
4949 public BusyPoolException(InetSocketAddress address, int queueSize) {
50- this(address, queueSize, null);
50+ this(address, buildMessage(address, queueSize), null);
5151 }
5252
53- private BusyPoolException(InetSocketAddress address, int queueSize, Throwable cause) {
54- super(buildMessage(address, queueSize), cause);
53+ public BusyPoolException(InetSocketAddress address, long timeout, TimeUnit unit) {
54+ this(address, buildMessage(address, timeout, unit), null);
55+ }
56+
57+ private BusyPoolException(InetSocketAddress address, String message, Throwable cause) {
58+ super(message, cause);
5559 this.address = address;
56- this.queueSize = queueSize;
5760 }
5861
5962 private static String buildMessage(InetSocketAddress address, int queueSize) {
@@ -62,6 +65,12 @@
6265 queueSize);
6366 }
6467
68+ private static String buildMessage(InetSocketAddress address, long timeout, TimeUnit unit) {
69+ return String.format("[%s] Pool is busy (no available connection and timed out after %d %s)",
70+ address.getAddress(),
71+ timeout, unit);
72+ }
73+
6574 @Override
6675 public InetAddress getHost() {
6776 return address.getAddress();
@@ -74,7 +83,7 @@
7483
7584 @Override
7685 public BusyPoolException copy() {
77- return new BusyPoolException(address, queueSize, this);
86+ return new BusyPoolException(address, getMessage(), this);
7887 }
7988
8089 }
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +104 −15
@@ -16,10 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import com.codahale.metrics.Gauge;
19-import com.datastax.driver.core.exceptions.BusyConnectionException;
20-import com.datastax.driver.core.exceptions.BusyPoolException;
21-import com.datastax.driver.core.exceptions.ConnectionException;
22-import com.datastax.driver.core.exceptions.DriverException;
19+import com.datastax.driver.core.exceptions.*;
2320 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
2421 import com.datastax.driver.core.utils.MoreFutures;
2522 import com.google.common.base.Predicate;
@@ -31,6 +28,7 @@
3128 import org.testng.annotations.Test;
3229
3330 import java.net.InetSocketAddress;
31+import java.util.Collection;
3432 import java.util.Collections;
3533 import java.util.Iterator;
3634 import java.util.List;
@@ -42,10 +40,13 @@
4240 import static com.datastax.driver.core.ConditionChecker.check;
4341 import static com.datastax.driver.core.PoolingOptions.NEW_CONNECTION_THRESHOLD_LOCAL_KEY;
4442 import static com.google.common.collect.Lists.newArrayList;
43+import static java.util.concurrent.TimeUnit.MILLISECONDS;
4544 import static java.util.concurrent.TimeUnit.SECONDS;
4645 import static org.mockito.Mockito.*;
4746 import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE;
47+import static org.scassandra.http.client.PrimingRequest.queryBuilder;
4848 import static org.scassandra.http.client.PrimingRequest.then;
49+import static org.scassandra.http.client.Result.server_error;
4950 import static org.testng.Assert.fail;
5051
5152 public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster {
@@ -115,13 +116,95 @@
115116 try {
116117 failedBorrow.getConnection();
117118 fail("Expected a BusyPoolException");
118- } catch (BusyPoolException e) {/*expected*/}
119+ } catch (BusyPoolException e) {
120+ assertThat(e).hasMessageContaining("reached its max size");
121+ }
122+ } finally {
123+ MockRequest.completeAll(allRequests);
124+ cluster.close();
125+ }
126+ }
127+
128+ /**
129+ * Ensures that if a fixed-sized pool has filled its core connections and reached a number of requests to cause
130+ * it to be enqueued, that if the request is not serviced within 100ms, a BusyPoolException is raised with a timeout.
131+ *
132+ * @jira_ticket JAVA-1371
133+ * @test_category connection:connection_pool
134+ * @since 3.0.7 3.1.4 3.2.0
135+ */
136+ @Test(groups = "short")
137+ public void should_reject_if_enqueued_and_timeout_reached() {
138+ Cluster cluster = createClusterBuilder().build();
139+ List<MockRequest> allRequests = newArrayList();
140+ try {
141+ HostConnectionPool pool = createPool(cluster, 1, 1);
142+ List<MockRequest> requests = MockRequest.sendMany(128, pool);
143+ allRequests.addAll(requests);
144+
145+ // pool is now full, this request will be enqueued
146+ MockRequest failedBorrow = MockRequest.send(pool, 100, 128);
147+ try {
148+ failedBorrow.getConnection();
149+ fail("Expected a BusyPoolException");
150+ } catch (BusyPoolException e) {
151+ assertThat(e).hasMessageContaining("timed out");
152+ }
119153 } finally {
120154 MockRequest.completeAll(allRequests);
121155 cluster.close();
122156 }
123157 }
124158
159+ /**
160+ * Validates that if a borrow request is enqueued into a pool for a Host that is currently
161+ * within the window of reconnecting after an error that the future tied to that query times out
162+ * after {@link PoolingOptions#setPoolTimeoutMillis(int)}.
163+ * <p>
164+ * This primarily serves to demonstrate that the use case described in JAVA-1371 is fixed by using
165+ * {@link Session#execute(Statement)} shortly after a server error on a connection.
166+ *
167+ * @jira_ticket JAVA-1371
168+ * @test_category connection:connection_pool
169+ * @since 3.0.7 3.1.4 3.2.0
170+ */
171+ @Test(groups = "short")
172+ public void should_not_hang_when_executing_sync_queries() {
173+ primingClient.prime(
174+ queryBuilder()
175+ .withQuery("server_error query")
176+ .withThen(then().withResult(server_error))
177+ .build()
178+ );
179+
180+ Cluster cluster = createClusterBuilder()
181+ .withReconnectionPolicy(new ConstantReconnectionPolicy(10000)).build();
182+ // reduce timeout so test runs faster.
183+ cluster.getConfiguration().getPoolingOptions().setPoolTimeoutMillis(500);
184+ try {
185+ Session session = cluster.connect();
186+ try {
187+ session.execute("server_error query");
188+ fail("Exception expected");
189+ } catch (Exception e) {
190+ // error is expected in this case.
191+ }
192+
193+ try {
194+ session.execute("this should not block indefinitely");
195+ } catch (NoHostAvailableException nhae) {
196+ // should raise a NHAE with a BusyPoolException.
197+ Collection<Throwable> errors = nhae.getErrors().values();
198+ assertThat(errors).hasSize(1);
199+ Throwable e = errors.iterator().next();
200+ assertThat(e).isInstanceOf(BusyPoolException.class);
201+ assertThat(e).hasMessageContaining("timed out");
202+ }
203+ } finally {
204+ cluster.close();
205+ }
206+ }
207+
125208 /**
126209 * Ensures that any enqueued connection borrow requests are failed when their associated connection pool closes.
127210 *
@@ -209,8 +292,11 @@
209292 try {
210293 Uninterruptibles.getUninterruptibly(queuedRequest.connectionFuture, 5, TimeUnit.SECONDS);
211294 count++;
212- } catch (TimeoutException te) {
295+ } catch (ExecutionException e) {
213296 // 128th request should timeout since all in flight requests are used.
297+ assertThat(e.getCause())
298+ .isInstanceOf(BusyPoolException.class)
299+ .hasMessageContaining("timed out after");
214300 assertThat(count).isEqualTo(128);
215301 break;
216302 }
@@ -1156,8 +1242,8 @@
11561242
11571243 // Should create up to core connections.
11581244 verify(factory, timeout(readTimeout).times(1)).open(any(HostConnectionPool.class));
1159- assertThat(pool.connections).hasSize(1);
11601245
1246+ assertPoolSize(pool, 1);
11611247 request.simulateSuccessResponse();
11621248 } finally {
11631249 cluster.close();
@@ -1271,7 +1357,11 @@
12711357 }
12721358
12731359 static MockRequest send(HostConnectionPool pool, int maxQueueSize) throws ConnectionException, BusyConnectionException {
1274- return new MockRequest(pool, maxQueueSize);
1360+ return send(pool, 5000, maxQueueSize);
1361+ }
1362+
1363+ static MockRequest send(HostConnectionPool pool, int timeoutMillis, int maxQueueSize) throws ConnectionException, BusyConnectionException {
1364+ return new MockRequest(pool, timeoutMillis, maxQueueSize);
12751365 }
12761366
12771367 private static List<MockRequest> sendMany(int count, HostConnectionPool pool) throws ConnectionException {
@@ -1312,8 +1402,8 @@
13121402 }
13131403 }
13141404
1315- private MockRequest(HostConnectionPool pool, int maxQueueSize) throws ConnectionException {
1316- this.connectionFuture = pool.borrowConnection(maxQueueSize);
1405+ private MockRequest(HostConnectionPool pool, int timeoutMillis, int maxQueueSize) throws ConnectionException {
1406+ this.connectionFuture = pool.borrowConnection(timeoutMillis, MILLISECONDS, maxQueueSize);
13171407 Futures.addCallback(this.connectionFuture, new MoreFutures.SuccessCallback<Connection>() {
13181408 @Override
13191409 public void onSuccess(Connection connection) {
@@ -1339,15 +1429,14 @@
13391429 responseHandler.cancelHandler();
13401430 }
13411431
1342- // Get the connection, assuming pool acquisition completed
13431432 Connection getConnection() {
13441433 try {
1345- if (!connectionFuture.isDone()) {
1346- throw new AssertionError("Borrow call did not complete");
1347- }
1348- return Uninterruptibles.getUninterruptibly(connectionFuture);
1434+ return Uninterruptibles.getUninterruptibly(connectionFuture, 500, MILLISECONDS);
13491435 } catch (ExecutionException e) {
13501436 throw Throwables.propagate(e.getCause());
1437+ } catch (TimeoutException e) {
1438+ fail("Timed out getting connection");
1439+ return null; // never reached
13511440 }
13521441 }
13531442
modified manual/pooling/README.md +10 −5
@@ -188,11 +188,15 @@
188188 requests), the acquisition attempt gets enqueued until a connection becomes
189189 available again.
190190
191-The size of that queue is controlled by [PoolingOptions.setMaxQueueSize][smqs].
192-If the queue has already reached its limit, further attempts to acquire a
193-connection will be rejected immediately: the driver will move on and try to
194-acquire a connection from the next host's pool. The limit can be set to 0 to
195-disable queueing entirely.
191+Two options control that queue: a maximum size ([PoolingOptions.setMaxQueueSize][smqs]) and a timeout
192+([PoolingOptions.setPoolTimeoutMillis][sptm]).
193+* if either option is set to zero, the attempt is rejected immediately;
194+* else if more than `maxQueueSize` requests are already waiting for a connection, the attempt is also rejected;
195+* otherwise, the attempt is enqueued; if a connection becomes available before `poolTimeoutMillis` has elapsed,
196+ then the attempt succeeds, otherwise it is rejected.
197+
198+If the attempt is rejected, the driver will move to the next host in the [query plan](../load_balancing/#query-plan),
199+and try to acquire a connection again.
196200
197201 If all hosts are busy with a full queue, the request will fail with a
198202 [NoHostAvailableException][nhae]. If you inspect the map returns by this
@@ -286,6 +290,7 @@
286290 [sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int-
287291 [rtm]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis--
288292 [smqs]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxQueueSize-int-
293+[sptm]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis-int-
289294 [nhae]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
290295 [getErrors]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html#getErrors--
291296 [get_state]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#getState--