Elffuss BraidHub

kikocis/java-driver public

Merge pull request #747 from datastax/java893_2

JAVA-893: Make connection pool non-blocking
Changeset0a5526490f498b75e8e3e2babf2aa8bf9b40cd8a612956f86a18154f301c12f7
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-09-23 22:42 -07:00
CommitterGitHub <noreply@github.com> · 2016-09-23 22:42 -07:00
Parents0960065b032a, 307a50ac64a5

Browse the files at this changeset

12 files changed

modified changelog/README.md +1 −0
@@ -16,6 +16,7 @@
1616 - [improvement] JAVA-1293: Make DecoderForStreamIdSize.MAX_FRAME_LENGTH configurable.
1717 - [improvement] JAVA-1053: Add a metric for authentication errors
1818 - [improvement] JAVA-1263: Eliminate unnecessary memory copies in FrameCompressor implementations.
19+- [improvement] JAVA-893: Make connection pool non-blocking
1920
2021
2122 ### 3.0.3
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +92 −23
@@ -19,6 +19,7 @@
1919 import com.datastax.driver.core.exceptions.*;
2020 import com.datastax.driver.core.utils.MoreFutures;
2121 import com.google.common.annotations.VisibleForTesting;
22+import com.google.common.base.Objects;
2223 import com.google.common.collect.Lists;
2324 import com.google.common.collect.MapMaker;
2425 import com.google.common.util.concurrent.*;
@@ -85,7 +86,9 @@
8586 final AtomicInteger inFlight = new AtomicInteger(0);
8687
8788 private final AtomicInteger writer = new AtomicInteger(0);
88- private volatile String keyspace;
89+
90+ private final AtomicReference<SetKeyspaceAttempt> targetKeyspace;
91+ private final SetKeyspaceAttempt defaultKeyspaceAttempt;
8992
9093 private volatile boolean isInitialized;
9194 private final AtomicBoolean isDefunct = new AtomicBoolean();
@@ -95,8 +98,9 @@
9598
9699 private final AtomicReference<Owner> ownerRef = new AtomicReference<Owner>();
97100
101+ private final ListenableFuture<Connection> thisFuture;
102+
98103 /**
99- * /**
100104 * Create a new connection to a Cassandra node and associate it with the given pool.
101105 *
102106 * @param name the connection name
@@ -111,6 +115,9 @@
111115 this.dispatcher = new Dispatcher();
112116 this.name = name;
113117 this.ownerRef.set(owner);
118+ this.thisFuture = Futures.immediateFuture(this);
119+ this.defaultKeyspaceAttempt = new SetKeyspaceAttempt(null, thisFuture);
120+ this.targetKeyspace = new AtomicReference<SetKeyspaceAttempt>(defaultKeyspaceAttempt);
114121 }
115122
116123 /**
@@ -418,7 +425,6 @@
418425 else if (Host.statesLogger.isDebugEnabled())
419426 Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage());
420427
421-
422428 Host host = factory.manager.metadata.getHost(address);
423429 if (host != null) {
424430 // Sometimes close() can be called before defunct(); avoid decrementing the connection count twice, but
@@ -452,14 +458,14 @@
452458 }
453459
454460 String keyspace() {
455- return keyspace;
461+ return targetKeyspace.get().keyspace;
456462 }
457463
458464 void setKeyspace(String keyspace) throws ConnectionException {
459465 if (keyspace == null)
460466 return;
461467
462- if (this.keyspace != null && this.keyspace.equals(keyspace))
468+ if (Objects.equal(keyspace(), keyspace))
463469 return;
464470
465471 try {
@@ -483,24 +489,59 @@
483489 }
484490 }
485491
486- ListenableFuture<Void> setKeyspaceAsync(final String keyspace) throws ConnectionException, BusyConnectionException {
487- logger.trace("{} Setting keyspace {}", this, keyspace);
488- // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already
489- Future future = write(new Requests.Query("USE \"" + keyspace + '"'));
490- return Futures.transform(future, new AsyncFunction<Message.Response, Void>() {
491- @Override
492- public ListenableFuture<Void> apply(Message.Response response) throws Exception {
493- if (response instanceof SetKeyspace) {
494- Connection.this.keyspace = ((SetKeyspace) response).keyspace;
495- return MoreFutures.VOID_SUCCESS;
496- } else if (response.type == ERROR) {
497- Responses.Error error = (Responses.Error) response;
498- throw defunct(error.asException(address));
499- } else {
500- throw defunct(new DriverInternalError("Unexpected response while setting keyspace: " + response));
501- }
492+ ListenableFuture<Connection> setKeyspaceAsync(final String keyspace) throws ConnectionException, BusyConnectionException {
493+ SetKeyspaceAttempt existingAttempt = targetKeyspace.get();
494+ if (Objects.equal(existingAttempt.keyspace, keyspace))
495+ return existingAttempt.future;
496+
497+ final SettableFuture<Connection> ksFuture = SettableFuture.create();
498+ final SetKeyspaceAttempt attempt = new SetKeyspaceAttempt(keyspace, ksFuture);
499+
500+ // Check for an existing keyspace attempt.
501+ while (true) {
502+ existingAttempt = targetKeyspace.get();
503+ // if existing attempts' keyspace matches what we are trying to set, use it.
504+ if (attempt.equals(existingAttempt)) {
505+ return existingAttempt.future;
506+ } else if (!existingAttempt.future.isDone()) {
507+ // If the existing attempt is still in flight, fail this attempt immediately.
508+ ksFuture.setException(new DriverException("Aborting attempt to set keyspace to '" + keyspace + "' since there is already an in flight attempt to set keyspace to '" + existingAttempt.keyspace + "'. "
509+ + "This can happen if you try to USE different keyspaces from the same session simultaneously."));
510+ return ksFuture;
511+ } else if (targetKeyspace.compareAndSet(existingAttempt, attempt)) {
512+ // Otherwise, if the existing attempt is done, start a new set keyspace attempt for the new keyspace.
513+ logger.debug("{} Setting keyspace {}", this, keyspace);
514+ // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already
515+ Future future = write(new Requests.Query("USE \"" + keyspace + '"'));
516+ Futures.addCallback(future, new FutureCallback<Message.Response>() {
517+
518+ @Override
519+ public void onSuccess(Message.Response response) {
520+ if (response instanceof SetKeyspace) {
521+ logger.debug("{} Keyspace set to {}", Connection.this, keyspace);
522+ ksFuture.set(Connection.this);
523+ } else {
524+ // Unset this attempt so new attempts may be made for the same keyspace.
525+ targetKeyspace.compareAndSet(attempt, defaultKeyspaceAttempt);
526+ if (response.type == ERROR) {
527+ Responses.Error error = (Responses.Error) response;
528+ ksFuture.setException(defunct(error.asException(address)));
529+ } else {
530+ ksFuture.setException(defunct(new DriverInternalError("Unexpected response while setting keyspace: " + response)));
531+ }
532+ }
533+ }
534+
535+ @Override
536+ public void onFailure(Throwable t) {
537+ targetKeyspace.compareAndSet(attempt, defaultKeyspaceAttempt);
538+ ksFuture.setException(t);
539+ }
540+ }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor());
541+
542+ return ksFuture;
502543 }
503- }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor());
544+ }
504545 }
505546
506547 /**
@@ -1181,6 +1222,34 @@
11811222 }
11821223 }
11831224
1225+ private class SetKeyspaceAttempt {
1226+ private final String keyspace;
1227+ private final ListenableFuture<Connection> future;
1228+
1229+ SetKeyspaceAttempt(String keyspace, ListenableFuture<Connection> future) {
1230+ this.keyspace = keyspace;
1231+ this.future = future;
1232+ }
1233+
1234+ @Override
1235+ public boolean equals(Object o) {
1236+ if (this == o)
1237+ return true;
1238+ if (!(o instanceof SetKeyspaceAttempt))
1239+ return false;
1240+
1241+ SetKeyspaceAttempt that = (SetKeyspaceAttempt) o;
1242+
1243+ return keyspace != null ? keyspace.equals(that.keyspace) : that.keyspace == null;
1244+
1245+ }
1246+
1247+ @Override
1248+ public int hashCode() {
1249+ return keyspace != null ? keyspace.hashCode() : 0;
1250+ }
1251+ }
1252+
11841253 static class Future extends AbstractFuture<Message.Response> implements RequestHandler.Callback {
11851254
11861255 private final Message.Request request;
@@ -1350,7 +1419,7 @@
13501419 pipeline.addLast("ssl", sslOptions.newSSLHandler(channel));
13511420 }
13521421
1353-// pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO));
1422+ // pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO));
13541423
13551424 pipeline.addLast("frameDecoder", new Frame.Decoder());
13561425 pipeline.addLast("frameEncoder", frameEncoder);
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +95 −113
@@ -16,6 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.AuthenticationException;
19+import com.datastax.driver.core.exceptions.BusyPoolException;
1920 import com.datastax.driver.core.exceptions.ConnectionException;
2021 import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
2122 import com.datastax.driver.core.utils.MoreFutures;
@@ -26,16 +27,10 @@
2627 import org.slf4j.Logger;
2728 import org.slf4j.LoggerFactory;
2829
29-import java.util.ArrayList;
30-import java.util.List;
31-import java.util.ListIterator;
32-import java.util.Set;
30+import java.util.*;
3331 import java.util.concurrent.*;
3432 import java.util.concurrent.atomic.AtomicInteger;
3533 import java.util.concurrent.atomic.AtomicReference;
36-import java.util.concurrent.locks.Condition;
37-import java.util.concurrent.locks.Lock;
38-import java.util.concurrent.locks.ReentrantLock;
3934
4035 import static com.datastax.driver.core.Connection.State.*;
4136
@@ -62,9 +57,8 @@
6257 @VisibleForTesting
6358 final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
6459
65- private volatile int waiter = 0;
66- private final Lock waitLock = new ReentrantLock(true);
67- private final Condition hasAvailableConnection = waitLock.newCondition();
60+ private final Queue<SettableFuture<Connection>> pendingBorrows = new ConcurrentLinkedQueue<SettableFuture<Connection>>();
61+ private final AtomicInteger pendingBorrowCount = new AtomicInteger();
6862
6963 private final Runnable newConnectionTask;
7064
@@ -81,7 +75,7 @@
8175 // following threshold, we just replace the connection by a new one.
8276 private final int minAllowedStreams;
8377
84- public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
78+ HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
8579 assert hostDistance != HostDistance.IGNORED;
8680 this.host = host;
8781 this.hostDistance = hostDistance;
@@ -196,17 +190,13 @@
196190 return manager.configuration().getPoolingOptions();
197191 }
198192
199- public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
193+ ListenableFuture<Connection> borrowConnection(int maxQueueSize) {
200194 Phase phase = this.phase.get();
201195 if (phase != Phase.READY)
202- // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
203- // That being said, maybe having a specific exception could be cleaner.
204- throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
196+ return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is " + phase));
205197
206198 if (connections.isEmpty()) {
207- if (!host.convictionPolicy.canReconnectNow())
208- throw new TimeoutException("Connection pool is empty, currently trying to reestablish connections");
209- else {
199+ if (host.convictionPolicy.canReconnectNow()) {
210200 int coreSize = options().getCoreConnectionsPerHost(hostDistance);
211201 if (coreSize == 0) {
212202 maybeSpawnNewConnection();
@@ -218,10 +208,7 @@
218208 manager.blockingExecutor().submit(newConnectionTask);
219209 }
220210 }
221- Connection c = waitForConnection(timeout, unit);
222- totalInFlight.incrementAndGet();
223- c.setKeyspace(manager.poolsState.keyspace);
224- return c;
211+ return enqueue(maxQueueSize);
225212 }
226213 }
227214
@@ -238,18 +225,17 @@
238225 if (leastBusy == null) {
239226 // We could have raced with a shutdown since the last check
240227 if (isClosed())
241- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
228+ return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
242229 // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between
243230 // the previous check to connections and now. But in that case, the line above will have trigger the creation of
244231 // a new connection, so just wait that connection and move on
245- leastBusy = waitForConnection(timeout, unit);
232+ return enqueue(maxQueueSize);
246233 } else {
247234 while (true) {
248235 int inFlight = leastBusy.inFlight.get();
249236
250237 if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) {
251- leastBusy = waitForConnection(timeout, unit);
252- break;
238+ return enqueue(maxQueueSize);
253239 }
254240
255241 if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
@@ -276,96 +262,37 @@
276262 maybeSpawnNewConnection();
277263 }
278264
279- leastBusy.setKeyspace(manager.poolsState.keyspace);
280- return leastBusy;
281- }
282-
283- private void awaitAvailableConnection(long timeout, TimeUnit unit) throws InterruptedException {
284- waitLock.lock();
285- waiter++;
286- try {
287- hasAvailableConnection.await(timeout, unit);
288- } finally {
289- waiter--;
290- waitLock.unlock();
291- }
292- }
293-
294- private void signalAvailableConnection() {
295- // Quick check if it's worth signaling to avoid locking
296- if (waiter == 0)
297- return;
298-
299- waitLock.lock();
300- try {
301- hasAvailableConnection.signal();
302- } finally {
303- waitLock.unlock();
304- }
265+ return leastBusy.setKeyspaceAsync(manager.poolsState.keyspace);
305266 }
306267
307- private void signalAllAvailableConnection() {
308- // Quick check if it's worth signaling to avoid locking
309- if (waiter == 0)
310- return;
311-
312- waitLock.lock();
313- try {
314- hasAvailableConnection.signalAll();
315- } finally {
316- waitLock.unlock();
268+ private ListenableFuture<Connection> enqueue(int maxQueueSize) {
269+ if (maxQueueSize == 0) {
270+ return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), 0));
317271 }
318- }
319272
320- private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
321- if (timeout == 0)
322- throw new TimeoutException("All connections are busy and pool timeout is 0");
323-
324- long start = System.nanoTime();
325- long remaining = timeout;
326- do {
327- try {
328- awaitAvailableConnection(remaining, unit);
329- } catch (InterruptedException e) {
330- Thread.currentThread().interrupt();
331- // If we're interrupted fine, check if there is a connection available but stop waiting otherwise
332- timeout = 0; // this will make us stop the loop if we don't get a connection right away
273+ while (true) {
274+ int count = pendingBorrowCount.get();
275+ if (count >= maxQueueSize) {
276+ return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), maxQueueSize));
333277 }
334-
335- if (isClosed())
336- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
337-
338- int minInFlight = Integer.MAX_VALUE;
339- Connection leastBusy = null;
340- for (Connection connection : connections) {
341- int inFlight = connection.inFlight.get();
342- if (inFlight < minInFlight) {
343- minInFlight = inFlight;
344- leastBusy = connection;
345- }
278+ if (pendingBorrowCount.compareAndSet(count, count + 1)) {
279+ break;
346280 }
281+ }
347282
348- // If we race with shutdown, leastBusy could be null. In that case we just loop and we'll throw on the next
349- // iteration anyway
350- if (leastBusy != null) {
351- while (true) {
352- int inFlight = leastBusy.inFlight.get();
353-
354- if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance)))
355- break;
356-
357- if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
358- return leastBusy;
359- }
360- }
283+ SettableFuture<Connection> future = SettableFuture.create();
284+ pendingBorrows.add(future);
361285
362- remaining = timeout - Cluster.timeSince(start, unit);
363- } while (remaining > 0);
286+ // If we raced with shutdown, make sure the future will be completed. This has no effect if it was properly
287+ // handled in closeAsync.
288+ if (phase.get() == Phase.CLOSING) {
289+ future.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
290+ }
364291
365- throw new TimeoutException("All connections are busy");
292+ return future;
366293 }
367294
368- public void returnConnection(Connection connection) {
295+ void returnConnection(Connection connection) {
369296 connection.inFlight.decrementAndGet();
370297 totalInFlight.decrementAndGet();
371298
@@ -384,7 +311,60 @@
384311 if (connection.maxAvailableStreams() < minAllowedStreams) {
385312 replaceConnection(connection);
386313 } else {
387- signalAvailableConnection();
314+ dequeue(connection);
315+ }
316+ }
317+ }
318+
319+ // When a connection gets returned to the pool, check if there are pending borrows that can be completed with it.
320+ private void dequeue(Connection connection) {
321+ while (!pendingBorrows.isEmpty()) {
322+
323+ // We can only reuse the connection if it's under its maximum number of inFlight requests.
324+ // Do this atomically, as we could be competing with other borrowConnection or dequeue calls.
325+ while (true) {
326+ int inFlight = connection.inFlight.get();
327+ if (inFlight >= Math.min(connection.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) {
328+ // Connection is full again, stop dequeuing
329+ return;
330+ }
331+ if (connection.inFlight.compareAndSet(inFlight, inFlight + 1)) {
332+ // We acquired the right to reuse the connection for one request, proceed
333+ break;
334+ }
335+ }
336+
337+ final SettableFuture<Connection> pendingBorrow = pendingBorrows.poll();
338+ if (pendingBorrow == null) {
339+ // Another thread has emptied the queue since our last check, restore the count
340+ connection.inFlight.decrementAndGet();
341+ } else {
342+ totalInFlight.incrementAndGet();
343+ pendingBorrowCount.decrementAndGet();
344+ // Ensure that the keyspace set on the connection is the one set on the pool state, in the general case it will be.
345+ ListenableFuture<Connection> setKeyspaceFuture = connection.setKeyspaceAsync(manager.poolsState.keyspace);
346+ // Slight optimization, if the keyspace was already correct the future will be complete, so simply complete it here.
347+ if (setKeyspaceFuture.isDone()) {
348+ try {
349+ pendingBorrow.set(Uninterruptibles.getUninterruptibly(setKeyspaceFuture));
350+ } catch (ExecutionException e) {
351+ pendingBorrow.setException(e.getCause());
352+ }
353+ } else {
354+ // Otherwise the keyspace did need to be set, tie the pendingBorrow future to the set keyspace completion.
355+ Futures.addCallback(setKeyspaceFuture, new FutureCallback<Connection>() {
356+
357+ @Override
358+ public void onSuccess(Connection c) {
359+ pendingBorrow.set(c);
360+ }
361+
362+ @Override
363+ public void onFailure(Throwable t) {
364+ pendingBorrow.setException(t);
365+ }
366+ });
367+ }
388368 }
389369 }
390370 }
@@ -453,6 +433,7 @@
453433 }
454434 logger.debug("Creating new connection on busy pool to {}", host);
455435 newConnection = manager.connectionFactory().open(this);
436+ newConnection.setKeyspace(manager.poolsState.keyspace);
456437 }
457438 connections.add(newConnection);
458439
@@ -465,7 +446,7 @@
465446 return false;
466447 }
467448
468- signalAvailableConnection();
449+ dequeue(newConnection);
469450 return true;
470451 } catch (InterruptedException e) {
471452 Thread.currentThread().interrupt();
@@ -600,11 +581,11 @@
600581 connection.closeAsync();
601582 }
602583
603- public final boolean isClosed() {
584+ final boolean isClosed() {
604585 return closeFuture.get() != null;
605586 }
606587
607- public final CloseFuture closeAsync() {
588+ final CloseFuture closeAsync() {
608589
609590 CloseFuture future = closeFuture.get();
610591 if (future != null)
@@ -612,8 +593,9 @@
612593
613594 phase.set(Phase.CLOSING);
614595
615- // Wake up all threads that wait
616- signalAllAvailableConnection();
596+ for (SettableFuture<Connection> pendingBorrow : pendingBorrows) {
597+ pendingBorrow.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
598+ }
617599
618600 future = new CloseFuture.Forwarding(discardAvailableConnections());
619601
@@ -622,7 +604,7 @@
622604 : closeFuture.get(); // We raced, it's ok, return the future that was actually set
623605 }
624606
625- public int opened() {
607+ int opened() {
626608 return open.get();
627609 }
628610
@@ -657,7 +639,7 @@
657639
658640 // This creates connections if we have less than core connections (if we
659641 // have more than core, connection will just get trash when we can).
660- public void ensureCoreConnections() {
642+ void ensureCoreConnections() {
661643 if (isClosed())
662644 return;
663645
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +40 −16
@@ -128,10 +128,16 @@
128128 public static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120;
129129
130130 /**
131- * The default value for {@link #getPoolTimeoutMillis()} ({@value}).
131+ * @deprecated see {@link #setPoolTimeoutMillis(int)}
132132 */
133+ @Deprecated
133134 public static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
134135
136+ /**
137+ * The default value for {@link #getMaxQueueSize()} ({@value}).
138+ */
139+ public static final int DEFAULT_MAX_QUEUE_SIZE = 256;
140+
135141 /**
136142 * The default value for {@link #getHeartbeatIntervalSeconds()} ({@value}).
137143 */
@@ -151,7 +157,7 @@
151157 private volatile int maxRequestsPerConnectionRemote = UNSET;
152158
153159 private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
154- private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
160+ private volatile int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE;
155161 private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
156162
157163 private volatile Executor initializationExecutor = DEFAULT_INITIALIZATION_EXECUTOR;
@@ -400,30 +406,48 @@
400406 }
401407
402408 /**
403- * Returns the timeout when trying to acquire a connection from a host's pool.
404- *
405- * @return the timeout.
409+ * @deprecated see {@link #setPoolTimeoutMillis(int)}. This method always returns 0.
406410 */
411+ @Deprecated
407412 public int getPoolTimeoutMillis() {
408- return poolTimeoutMillis;
413+ return 0;
414+ }
415+
416+ /**
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.
419+ */
420+ @Deprecated
421+ public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) {
422+ return this;
423+ }
424+
425+ /**
426+ * Returns the maximum number of requests that get enqueued if no connection is available.
427+ *
428+ * @return the maximum queue size.
429+ */
430+ public int getMaxQueueSize() {
431+ return maxQueueSize;
409432 }
410433
411434 /**
412- * Sets the timeout when trying to acquire a connection from a host's pool.
435+ * Sets the maximum number of requests that get enqueued if no connection is available.
413436 * <p/>
414- * If no connection is available within that time, the driver will try the
415- * next host from the query plan.
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.
416439 * <p/>
417- * The default is 5 seconds. If this option is set to zero, the driver won't wait at all.
440+ * The default value is {@value DEFAULT_MAX_QUEUE_SIZE}. If this option is set to zero, the driver will never
441+ * enqueue requests.
418442 *
419- * @param poolTimeoutMillis the new value in milliseconds.
443+ * @param maxQueueSize the new value.
420444 * @return this {@code PoolingOptions}
421- * @throws IllegalArgumentException if the timeout is negative.
445+ * @throws IllegalArgumentException if the value is negative.
422446 */
423- public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) {
424- if (poolTimeoutMillis < 0)
425- throw new IllegalArgumentException("Pool timeout must be positive");
426- this.poolTimeoutMillis = poolTimeoutMillis;
447+ public PoolingOptions setMaxQueueSize(int maxQueueSize) {
448+ if (maxQueueSize < 0)
449+ throw new IllegalArgumentException("Max queue size must be positive");
450+ this.maxQueueSize = maxQueueSize;
427451 return this;
428452 }
429453
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +61 −57
@@ -21,6 +21,9 @@
2121 import com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type;
2222 import com.datastax.driver.core.policies.SpeculativeExecutionPolicy.SpeculativeExecutionPlan;
2323 import com.google.common.collect.Sets;
24+import com.google.common.util.concurrent.FutureCallback;
25+import com.google.common.util.concurrent.Futures;
26+import com.google.common.util.concurrent.ListenableFuture;
2427 import io.netty.util.Timeout;
2528 import io.netty.util.TimerTask;
2629 import org.slf4j.Logger;
@@ -108,7 +111,7 @@
108111
109112 SpeculativeExecution execution = new SpeculativeExecution(request, position);
110113 runningExecutions.add(execution);
111- execution.sendRequest();
114+ execution.findNextHostAndQuery();
112115 }
113116
114117 private void scheduleExecution(long delayMillis) {
@@ -261,12 +264,10 @@
261264 logger.trace("[{}] Starting", id);
262265 }
263266
264- void sendRequest() {
267+ void findNextHostAndQuery() {
265268 try {
266269 Host host;
267270 while (!isDone.get() && (host = queryPlan.next()) != null && !queryStateRef.get().isCancelled()) {
268- if (logger.isTraceEnabled())
269- logger.trace("[{}] Querying node {}", id, host);
270271 if (query(host))
271272 return;
272273 }
@@ -278,48 +279,63 @@
278279 }
279280
280281 private boolean query(final Host host) {
281- HostConnectionPool currentPool = manager.pools.get(host);
282- if (currentPool == null || currentPool.isClosed())
282+ HostConnectionPool pool = manager.pools.get(host);
283+ if (pool == null || pool.isClosed())
283284 return false;
284285
286+ if (logger.isTraceEnabled())
287+ logger.trace("[{}] Querying node {}", id, host);
288+
285289 if (allowSpeculativeExecutions && nextExecutionScheduled.compareAndSet(false, true))
286290 scheduleExecution(speculativeExecutionPlan.nextExecution(host));
287291
288- Connection connection = null;
289- try {
290- connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS);
291- if (current != null) {
292- if (triedHosts == null)
293- triedHosts = new CopyOnWriteArrayList<Host>();
294- triedHosts.add(current);
292+ ListenableFuture<Connection> connectionFuture = pool.borrowConnection(
293+ manager.configuration().getPoolingOptions().getMaxQueueSize());
294+ Futures.addCallback(connectionFuture, new FutureCallback<Connection>() {
295+ @Override
296+ public void onSuccess(Connection connection) {
297+ if (current != null) {
298+ if (triedHosts == null)
299+ triedHosts = new CopyOnWriteArrayList<Host>();
300+ triedHosts.add(current);
301+ }
302+ current = host;
303+ try {
304+ write(connection, SpeculativeExecution.this);
305+ } catch (ConnectionException e) {
306+ // If we have any problem with the connection, move to the next node.
307+ if (metricsEnabled())
308+ metrics().getErrorMetrics().getConnectionErrors().inc();
309+ if (connection != null)
310+ connection.release();
311+ logError(host.getSocketAddress(), e);
312+ findNextHostAndQuery();
313+ } catch (BusyConnectionException e) {
314+ // The pool shouldn't have give us a busy connection unless we've maxed up the pool, so move on to the next host.
315+ connection.release();
316+ logError(host.getSocketAddress(), e);
317+ findNextHostAndQuery();
318+ } catch (RuntimeException e) {
319+ if (connection != null)
320+ connection.release();
321+ logger.error("Unexpected error while querying " + host.getAddress(), e);
322+ logError(host.getSocketAddress(), e);
323+ findNextHostAndQuery();
324+ }
295325 }
296- current = host;
297- write(connection, this);
298- return true;
299- } catch (ConnectionException e) {
300- // If we have any problem with the connection, move to the next node.
301- if (metricsEnabled())
302- metrics().getErrorMetrics().getConnectionErrors().inc();
303- if (connection != null)
304- connection.release();
305- logError(host.getSocketAddress(), e);
306- return false;
307- } catch (BusyConnectionException e) {
308- // The pool shouldn't have give us a busy connection unless we've maxed up the pool, so move on to the next host.
309- connection.release();
310- logError(host.getSocketAddress(), e);
311- return false;
312- } catch (TimeoutException e) {
313- // We timeout, log it but move to the next node.
314- logError(host.getSocketAddress(), new DriverException("Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)", e));
315- return false;
316- } catch (RuntimeException e) {
317- if (connection != null)
318- connection.release();
319- logger.error("Unexpected error while querying " + host.getAddress(), e);
320- logError(host.getSocketAddress(), e);
321- return false;
322- }
326+
327+ @Override
328+ public void onFailure(Throwable t) {
329+ if (t instanceof BusyPoolException) {
330+ logError(host.getSocketAddress(), t);
331+ } else {
332+ logger.error("Unexpected error while querying " + host.getAddress(), t);
333+ logError(host.getSocketAddress(), t);
334+ }
335+ findNextHostAndQuery();
336+ }
337+ });
338+ return true;
323339 }
324340
325341 private void write(Connection connection, Connection.ResponseCallback responseCallback) throws ConnectionException, BusyConnectionException {
@@ -382,23 +398,11 @@
382398 if (newConsistencyLevel != null)
383399 this.retryConsistencyLevel = newConsistencyLevel;
384400
385- // We should not retry on the current thread as this will be an IO thread.
386- manager.executor().execute(new Runnable() {
387- @Override
388- public void run() {
389- if (queryStateRef.get().isCancelled())
390- return;
391- try {
392- if (retryCurrent) {
393- if (query(h))
394- return;
395- }
396- sendRequest();
397- } catch (Exception e) {
398- setFinalException(null, new DriverInternalError("Unexpected exception while retrying query", e));
399- }
400- }
401- });
401+ if (queryStateRef.get().isCancelled())
402+ return;
403+
404+ if (!retryCurrent || !query(h))
405+ findNextHostAndQuery();
402406 }
403407
404408 private void logError(InetSocketAddress address, Throwable exception) {
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +23 −15
@@ -623,22 +623,30 @@
623623
624624 try {
625625 // Preparing is not critical: if it fails, it will fix itself later when the user tries to execute
626- // the prepared query. So don't block if no connection is available, simply abort.
627- final Connection c = entry.getValue().borrowConnection(0, TimeUnit.MILLISECONDS);
628- ListenableFuture<Response> future = c.write(new Requests.Prepare(query));
629- Futures.addCallback(future, new FutureCallback<Response>() {
630- @Override
631- public void onSuccess(Response result) {
632- c.release();
633- }
626+ // the prepared query. So don't wait if no connection is available, simply abort.
627+ ListenableFuture<Connection> connectionFuture = entry.getValue().borrowConnection(0);
628+ ListenableFuture<Response> prepareFuture = Futures.transform(connectionFuture,
629+ new AsyncFunction<Connection, Response>() {
630+ @Override
631+ public ListenableFuture<Response> apply(final Connection c) throws Exception {
632+ Connection.Future responseFuture = c.write(new Requests.Prepare(query));
633+ Futures.addCallback(responseFuture, new FutureCallback<Response>() {
634+ @Override
635+ public void onSuccess(Response result) {
636+ c.release();
637+ }
634638
635- @Override
636- public void onFailure(Throwable t) {
637- logger.debug(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), t);
638- c.release();
639- }
640- });
641- futures.add(future);
639+ @Override
640+ public void onFailure(Throwable t) {
641+ logger.debug(String.format("Unexpected error while preparing query (%s) on %s",
642+ query, entry.getKey()), t);
643+ c.release();
644+ }
645+ });
646+ return responseFuture;
647+ }
648+ });
649+ futures.add(prepareFuture);
642650 } catch (Exception e) {
643651 // Again, not being able to prepare the query right now is no big deal, so just ignore
644652 }
added driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyPoolException.java +80 −0
@@ -0,0 +1,80 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.exceptions;
17+
18+import com.datastax.driver.core.HostDistance;
19+import com.datastax.driver.core.Statement;
20+
21+import java.net.InetAddress;
22+import java.net.InetSocketAddress;
23+
24+/**
25+ * Indicates that a connection pool has run out of available connections.
26+ * <p/>
27+ * This happens if the pool has no connections (for example if it's currently reconnecting to its host), or if all
28+ * connections have reached their maximum number of in flight queries. The query will be retried on the next host in the
29+ * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#newQueryPlan(String, Statement) query plan}.
30+ * <p/>
31+ * This exception is a symptom that the driver is experiencing a high workload. If it happens regularly on all hosts,
32+ * you should consider tuning one (or a combination of) the following pooling options:
33+ * <ul>
34+ * <li>{@link com.datastax.driver.core.PoolingOptions#setMaxRequestsPerConnection(HostDistance, int)}: maximum number of
35+ * requests per connection;</li>
36+ * <li>{@link com.datastax.driver.core.PoolingOptions#setMaxConnectionsPerHost(HostDistance, int)}: maximum number of
37+ * connections in the pool;</li>
38+ * <li>{@link com.datastax.driver.core.PoolingOptions#setMaxQueueSize(int)}: maximum number of enqueued requests before
39+ * this exception is thrown.</li>
40+ * </ul>
41+ */
42+public class BusyPoolException extends DriverException implements CoordinatorException {
43+
44+ private static final long serialVersionUID = 0;
45+
46+ private final InetSocketAddress address;
47+ private final int queueSize;
48+
49+ public BusyPoolException(InetSocketAddress address, int queueSize) {
50+ this(address, queueSize, null);
51+ }
52+
53+ private BusyPoolException(InetSocketAddress address, int queueSize, Throwable cause) {
54+ super(buildMessage(address, queueSize), cause);
55+ this.address = address;
56+ this.queueSize = queueSize;
57+ }
58+
59+ private static String buildMessage(InetSocketAddress address, int queueSize) {
60+ return String.format("[%s] Pool is busy (no available connection and the queue has reached its max size %d)",
61+ address.getAddress(),
62+ queueSize);
63+ }
64+
65+ @Override
66+ public InetAddress getHost() {
67+ return address.getAddress();
68+ }
69+
70+ @Override
71+ public InetSocketAddress getAddress() {
72+ return address;
73+ }
74+
75+ @Override
76+ public BusyPoolException copy() {
77+ return new BusyPoolException(address, queueSize, this);
78+ }
79+
80+}
modified driver-core/src/test/java/com/datastax/driver/core/ConnectionReleaseTest.java +1 −3
@@ -110,9 +110,7 @@
110110 }
111111 });
112112
113- // Wait for up to pool timeout for response. If future is not complete by then, we can assume
114- // that it is likely that the execute is hung because the connection wasn't released yet.
115- long waitTimeInMs = cluster.getConfiguration().getPoolingOptions().getPoolTimeoutMillis();
113+ long waitTimeInMs = 2000;
116114 try {
117115 ResultSet result = future.get(waitTimeInMs, TimeUnit.MILLISECONDS);
118116 assertThat(result.one().getString("n")).isEqualTo("world");
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +421 −144
@@ -16,10 +16,11 @@
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.ConnectionException;
19+import com.datastax.driver.core.exceptions.*;
2120 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
21+import com.datastax.driver.core.utils.MoreFutures;
2222 import com.google.common.base.Predicate;
23+import com.google.common.base.Throwables;
2324 import com.google.common.util.concurrent.*;
2425 import org.scassandra.cql.PrimitiveType;
2526 import org.scassandra.http.client.PrimingRequest;
@@ -27,6 +28,7 @@
2728 import org.testng.annotations.Test;
2829
2930 import java.net.InetSocketAddress;
31+import java.util.Collections;
3032 import java.util.Iterator;
3133 import java.util.List;
3234 import java.util.concurrent.*;
@@ -35,8 +37,8 @@
3537
3638 import static com.datastax.driver.core.Assertions.assertThat;
3739 import static com.datastax.driver.core.ConditionChecker.check;
40+import static com.datastax.driver.core.PoolingOptions.NEW_CONNECTION_THRESHOLD_LOCAL_KEY;
3841 import static com.google.common.collect.Lists.newArrayList;
39-import static java.util.Collections.singletonList;
4042 import static java.util.concurrent.TimeUnit.SECONDS;
4143 import static org.mockito.Mockito.*;
4244 import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE;
@@ -45,6 +47,9 @@
4547
4648 public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster {
4749
50+ static final Integer NEW_CONNECTION_THRESHOLD = PoolingOptions.DEFAULTS.get(ProtocolVersion.V1)
51+ .get(NEW_CONNECTION_THRESHOLD_LOCAL_KEY);
52+
4853 @BeforeClass(groups = {"short", "long"})
4954 public void reinitializeCluster() {
5055 // Don't use the provided cluster, each test will create its own instead.
@@ -67,136 +72,317 @@
6772 }).becomesTrue();
6873 }
6974
70- /**
71- * Sends 101 requests on pool, asserting that the connection used is in expectedConnections, except for the last request.
72- */
73- private List<MockRequest> fillConnectionToThreshold(HostConnectionPool pool, List<Connection> expectedConnections) throws ConnectionException, BusyConnectionException, TimeoutException {
74- List<MockRequest> requests = sendRequests(100, pool, expectedConnections);
75- requests.add(MockRequest.send(pool));
76- return requests;
75+ private void assertBorrowedConnections(Iterable<MockRequest> requests, List<Connection> expectedConnections) {
76+ for (MockRequest request : requests) {
77+ assertThat(expectedConnections).contains(request.getConnection());
78+ }
79+ }
80+
81+ private void assertBorrowedConnection(Iterable<MockRequest> requests, Connection expectedConnection) {
82+ assertBorrowedConnections(requests, Collections.singletonList(expectedConnection));
7783 }
7884
7985 /**
80- * Sends count requests on pool.
86+ * Ensures that if a fixed-sized pool has filled its core connections and reached its maximum number of enqueued
87+ * requests, then borrowConnection will fail instead of creating a new connection.
88+ *
89+ * @jira_ticket JAVA-419
90+ * @test_category connection:connection_pool
91+ * @since 2.0.10, 2.1.6
8192 */
82- private List<MockRequest> sendRequests(int count, HostConnectionPool pool) throws ConnectionException, BusyConnectionException, TimeoutException {
83- return sendRequests(count, pool, null);
93+ @Test(groups = "short")
94+ public void fixed_size_pool_should_fill_its_core_connections_and_queue_and_then_reject() {
95+ Cluster cluster = createClusterBuilder().build();
96+ List<MockRequest> allRequests = newArrayList();
97+ try {
98+ HostConnectionPool pool = createPool(cluster, 2, 2);
99+ int maxQueueSize = 256;
100+
101+ assertThat(pool.connections.size()).isEqualTo(2);
102+ List<Connection> coreConnections = newArrayList(pool.connections);
103+ // fill connections
104+ List<MockRequest> requests = MockRequest.sendMany(2 * 128, pool);
105+ assertBorrowedConnections(requests, coreConnections);
106+ allRequests.addAll(requests);
107+ // fill queue
108+ allRequests.addAll(MockRequest.sendMany(maxQueueSize, pool, maxQueueSize));
109+
110+ // add one more request, it should be rejected because the queue is full
111+ MockRequest failedBorrow = MockRequest.send(pool, maxQueueSize);
112+ try {
113+ failedBorrow.getConnection();
114+ fail("Expected a BusyPoolException");
115+ } catch (BusyPoolException e) {/*expected*/}
116+ } finally {
117+ MockRequest.completeAll(allRequests);
118+ cluster.close();
119+ }
84120 }
85121
86122 /**
87- * Sends count requests on pool, asserting that the connection used is in expectedConnections.
123+ * Ensures that any enqueued connection borrow requests are failed when their associated connection pool closes.
124+ *
125+ * @jira_ticket JAVA-839
126+ * @test_category connection:connection_pool
127+ * @since 3.0.4, 3.1.1
88128 */
89- private List<MockRequest> sendRequests(int count, HostConnectionPool pool, List<Connection> expectedConnections) throws ConnectionException, BusyConnectionException, TimeoutException {
129+ @Test(groups = "short")
130+ public void requests_with_enqueued_borrow_requests_should_be_failed_when_pool_closes() {
131+ Cluster cluster = createClusterBuilder().build();
90132 List<MockRequest> requests = newArrayList();
91- for (int i = 0; i < count; i++) {
92- MockRequest request = MockRequest.send(pool);
93- requests.add(request);
94- if (expectedConnections != null)
95- assertThat(expectedConnections).contains(request.connection);
96- }
97- return requests;
133+ try {
134+ HostConnectionPool pool = createPool(cluster, 2, 2);
135+ int maxQueueSize = 256;
136+
137+ assertThat(pool.connections.size()).isEqualTo(2);
138+ List<Connection> coreConnections = newArrayList(pool.connections);
139+ // fill connections
140+ requests = MockRequest.sendMany(2 * 128, pool);
141+ assertBorrowedConnections(requests, coreConnections);
142+ // fill queue
143+ List<MockRequest> queuedRequests = MockRequest.sendMany(maxQueueSize, pool, maxQueueSize);
144+
145+ // Closing the pool should fail all queued connections.
146+ pool.closeAsync();
147+
148+ for (MockRequest queuedRequest : queuedRequests) {
149+ // Future should be completed.
150+ assertThat(queuedRequest.connectionFuture.isDone()).isTrue();
151+ try {
152+ // Future should fail as result of the pool closing.
153+ queuedRequest.getConnection();
154+ fail("Expected a ConnectionException");
155+ } catch (ConnectionException e) {/*expected*/}
156+ }
157+ } finally {
158+ MockRequest.completeAll(requests);
159+ cluster.close();
160+ }
98161 }
99162
100163 /**
101- * Completes count requests by simulating a successful response.
164+ * Validates that if the keyspace tied to the Session's pool state is different than the keyspace on the connection
165+ * being used in dequeue that {@link Connection#setKeyspaceAsync(String)} is set on that connection and that
166+ * "USE keyspace" is only called once since setKeyspaceAsync should not attempt setting the keyspace if there is
167+ * already a request inflight that is doing this.
168+ *
169+ * @jira_ticket JAVA-839
170+ * @test_category connection:connection_pool
171+ * @since 3.0.4, 3.1.1
102172 */
103- private void completeRequests(int count, List<MockRequest> requests) {
104- Iterator<MockRequest> requestIt = requests.iterator();
105- for (int i = 0; i < count; i++) {
106- if (requestIt.hasNext()) {
107- MockRequest request = requestIt.next();
108- request.simulateSuccessResponse();
109- requestIt.remove();
110- } else {
111- break;
173+ @Test(groups = "short")
174+ public void should_adjust_connection_keyspace_on_dequeue_if_pool_state_is_different() throws TimeoutException, ExecutionException {
175+ Cluster cluster = createClusterBuilder().build();
176+ List<MockRequest> requests = newArrayList();
177+ try {
178+ HostConnectionPool pool = createPool(cluster, 1, 1);
179+ int maxQueueSize = 256;
180+
181+ assertThat(pool.connections.size()).isEqualTo(1);
182+ List<Connection> coreConnections = newArrayList(pool.connections);
183+ // fill connections
184+ requests = MockRequest.sendMany(128, pool);
185+ assertBorrowedConnections(requests, coreConnections);
186+ // fill queue
187+ List<MockRequest> queuedRequests = MockRequest.sendMany(maxQueueSize, pool, maxQueueSize);
188+
189+ // Wait for connections to be borrowed before changing keyspace.
190+ for (MockRequest request : requests) {
191+ Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS);
192+ }
193+ // Simulate change of keyspace on pool. Prime a delay so existing requests can complete beforehand.
194+ primingClient.prime(PrimingRequest.queryBuilder().withQuery("USE \"newkeyspace\"").withThen(PrimingRequest.then().withFixedDelay(2000L)));
195+ pool.manager.poolsState.setKeyspace("newkeyspace");
196+
197+ // Complete all requests, this should cause dequeue on connection.
198+ MockRequest.completeAll(requests);
199+
200+ // Check the status on queued request's connection futures. We expect that dequeue should
201+ // be called when connection is released by previous requests completing, and that one set
202+ // keyspace attempt should be tried.
203+
204+ // Because Scassandra currently returns a 'ROWS' response for set keyspace, the attempt
205+ // will fail, and thus the enqueued connection futures will fail in the following ways:
206+ // 1. DriverInternalError for set keyspace returning 'ROWS' response
207+ // 2. TransportException for connection being closed, when this happens we stop checking these futures.
208+ // 3. Never completing because no connections are available.
209+ boolean timeoutAcceptable = false;
210+ for (MockRequest queuedRequest : queuedRequests) {
211+ try {
212+ Uninterruptibles.getUninterruptibly(queuedRequest.connectionFuture, 5, TimeUnit.SECONDS);
213+ fail("Expected an exception (because Scassandra doesn't support 'USE keyspace'");
214+ } catch (ExecutionException e) {
215+ try {
216+ throw e.getCause();
217+ } catch (DriverInternalError die) {
218+ assertThat(die.getMessage()).contains("Unexpected response while setting keyspace");
219+ // Subsequent futures may timeout because the connection is closed.
220+ timeoutAcceptable = true;
221+ } catch (TransportException ce) {
222+ /* expected, Scassandra returning a ROWS response for 'USE keyspace' should defunct and close the connection */
223+ // all remaining futures will timeout since there are no remaining connections.
224+ break;
225+ } catch (Throwable t) {
226+ fail("Unexpected cause of future failing", t);
227+ }
228+ } catch (TimeoutException te) {
229+ assertThat(timeoutAcceptable).isTrue();
230+ break;
231+ }
112232 }
233+
234+ // We should only have gotten one 'USE newkeyspace' query since Connection#setKeyspaceAsync should only do
235+ // this once if there is already a request in flight.
236+ assertThat(activityClient.retrieveQueries()).extractingResultOf("getQuery").containsOnlyOnce("USE \"newkeyspace\"");
237+ } finally {
238+ MockRequest.completeAll(requests);
239+ cluster.close();
113240 }
114241 }
115242
116243 /**
117- * Completes all requests by simulating a successful response.
244+ * Ensures that on borrowConnection if a set keyspace attempt is in progress on that connection for a different keyspace than the
245+ * pool state that the borrowConnection future returned is failed.
246+ *
247+ * @jira_ticket JAVA-839
248+ * @test_category connection:connection_pool
249+ * @since 3.0.4, 3.1.1
118250 */
119- private void completeRequests(List<MockRequest> requests) {
120- for (MockRequest request : requests) {
121- request.simulateSuccessResponse();
251+ @Test(groups = "short")
252+ public void should_fail_in_borrowConnection_when_setting_keyspace_and_another_set_keyspace_attempt_is_in_flight() throws TimeoutException {
253+ Cluster cluster = createClusterBuilder().build();
254+ try {
255+ HostConnectionPool pool = createPool(cluster, 1, 1);
256+
257+ // Respond to setting as slowks very slowly.
258+ primingClient.prime(PrimingRequest.queryBuilder().withQuery("USE \"slowks\"").withThen(PrimingRequest.then().withFixedDelay(5000L)));
259+
260+ Connection connection = pool.connections.get(0);
261+
262+ connection.setKeyspaceAsync("slowks");
263+
264+ // Simulate change of keyspace on pool.
265+ pool.manager.poolsState.setKeyspace("newks");
266+
267+ MockRequest request = MockRequest.send(pool);
268+
269+ try {
270+ Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS);
271+ fail("Should have thrown exception");
272+ } catch (ExecutionException e) {
273+ assertThat(e.getCause()).isInstanceOf(DriverException.class);
274+ assertThat(e.getCause().getMessage()).contains("Aborting attempt to set keyspace to 'newks' since there is already an in flight attempt to set keyspace to 'slowks'.");
275+ }
276+ } finally {
277+ cluster.close();
122278 }
123279 }
124280
125281 /**
126- * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead
127- * of creating a new connection.
282+ * Ensures that while dequeuing borrow connection requests that if a set keyspace attempt is in progress on that connection for a difference
283+ * keyspace than the pool state that the future for that borrow attempt is failed.
128284 *
129- * @jira_ticket JAVA-419
285+ * @jira_ticket JAVA-839
130286 * @test_category connection:connection_pool
131- * @since 2.0.10, 2.1.6
287+ * @since 3.0.4, 3.1.1
132288 */
133289 @Test(groups = "short")
134- public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException, BusyConnectionException {
290+ public void should_fail_in_dequeue_when_setting_keyspace_and_another_set_keyspace_attempt_is_in_flight() throws ExecutionException, TimeoutException {
135291 Cluster cluster = createClusterBuilder().build();
136292 List<MockRequest> requests = newArrayList();
137293 try {
138- HostConnectionPool pool = createPool(cluster, 2, 2);
294+ // Limit requests per connection to 100 so we don't exhaust stream ids.
295+ cluster.getConfiguration().getPoolingOptions().setMaxRequestsPerConnection(HostDistance.LOCAL, 100);
296+ HostConnectionPool pool = createPool(cluster, 1, 1);
297+ int maxQueueSize = 256;
139298
140- assertThat(pool.connections.size()).isEqualTo(2);
299+ assertThat(pool.connections.size()).isEqualTo(1);
141300 List<Connection> coreConnections = newArrayList(pool.connections);
142- requests.addAll(sendRequests(256, pool, coreConnections));
301+
302+ // fill connections
303+ requests = MockRequest.sendMany(100, pool);
304+ assertBorrowedConnections(requests, coreConnections);
305+
306+ // send a request that will be queued.
307+ MockRequest queuedRequest = MockRequest.send(pool, maxQueueSize);
308+
309+ // Wait for connections to be borrowed before changing keyspace.
310+ for (MockRequest request : requests) {
311+ Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS);
312+ }
313+
314+ // Respond to setting as slowks very slowly.
315+ primingClient.prime(PrimingRequest.queryBuilder().withQuery("USE \"slowks\"").withThen(PrimingRequest.then().withFixedDelay(5000L)));
316+ Connection connection = pool.connections.get(0);
317+ connection.setKeyspaceAsync("slowks");
318+
319+ // Simulate change of keyspace on pool.
320+ pool.manager.poolsState.setKeyspace("newkeyspace");
321+
322+ // Complete all requests, this should cause dequeue on connection.
323+ MockRequest.completeAll(requests);
143324
144325 try {
145- MockRequest.send(pool);
146- Assertions.fail("Expected a TimeoutException");
147- } catch (TimeoutException e) { /*expected*/}
326+ Uninterruptibles.getUninterruptibly(queuedRequest.connectionFuture, 5, TimeUnit.SECONDS);
327+ fail("Should have thrown exception");
328+ } catch (ExecutionException e) {
329+ assertThat(e.getCause()).isInstanceOf(DriverException.class);
330+ assertThat(e.getCause().getMessage()).contains("Aborting attempt to set keyspace to 'newkeyspace' since there is already an in flight attempt to set keyspace to 'slowks'.");
331+ }
332+
148333 } finally {
149- completeRequests(requests);
334+ MockRequest.completeAll(requests);
150335 cluster.close();
151336 }
152337 }
153338
154339 /**
155340 * Ensures that if a variable-sized pool has filled up to its maximum connections that borrowConnection will
156- * timeout instead of creating a new connection.
341+ * return a failed future instead of creating a new connection.
157342 *
158343 * @jira_ticket JAVA-419
159344 * @test_category connection:connection_pool
160345 * @since 2.0.10, 2.1.6
161346 */
162347 @Test(groups = "short")
163- public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws Exception {
348+ public void variable_size_pool_should_fill_its_connections_and_then_reject() throws Exception {
164349 Cluster cluster = createClusterBuilder().build();
165- List<MockRequest> requests = newArrayList();
350+ List<MockRequest> allRequests = newArrayList();
166351 try {
167352 HostConnectionPool pool = createPool(cluster, 1, 2);
168353 Connection.Factory factory = spy(cluster.manager.connectionFactory);
169354 cluster.manager.connectionFactory = factory;
170355
171356 assertThat(pool.connections.size()).isEqualTo(1);
172- List<Connection> coreConnections = newArrayList(pool.connections);
357+ Connection coreConnection = pool.connections.get(0);
173358
174359 // Fill enough connections to hit the threshold.
175- requests.addAll(fillConnectionToThreshold(pool, coreConnections));
360+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
361+ assertBorrowedConnection(requests, coreConnection);
362+ allRequests.addAll(requests);
363+ allRequests.add(MockRequest.send(pool));
176364
177365 // Allow time for new connection to be spawned.
178366 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
179367 assertPoolSize(pool, 2);
180368
181369 // Borrow more and ensure the connection returned is a non-core connection.
182- for (int i = 0; i < 100; i++) {
370+ for (int i = 0; i < NEW_CONNECTION_THRESHOLD; i++) {
183371 MockRequest request = MockRequest.send(pool);
184- assertThat(coreConnections).doesNotContain(request.connection);
185- requests.add(request);
372+ assertThat(request.getConnection()).isNotEqualTo(coreConnection);
373+ allRequests.add(request);
186374 }
187375
188376 // Fill remaining connections (28 + 28) - 1
189- requests.addAll(sendRequests(55, pool));
377+ allRequests.addAll(MockRequest.sendMany(55, pool));
190378
191- boolean timedOut = false;
379+ MockRequest failedBorrow = MockRequest.send(pool);
192380 try {
193- MockRequest.send(pool);
194- } catch (TimeoutException e) {
195- timedOut = true;
196- }
197- assertThat(timedOut).isTrue();
381+ failedBorrow.getConnection();
382+ fail("Expected a BusyPoolException");
383+ } catch (BusyPoolException e) { /*expected*/}
198384 } finally {
199- completeRequests(requests);
385+ MockRequest.completeAll(allRequests);
200386 cluster.close();
201387 }
202388 }
@@ -211,7 +397,7 @@
211397 @Test(groups = "short")
212398 public void should_add_extra_connection_when_core_full() throws Exception {
213399 Cluster cluster = createClusterBuilder().build();
214- List<MockRequest> requests = newArrayList();
400+ List<MockRequest> allRequests = newArrayList();
215401 try {
216402 HostConnectionPool pool = createPool(cluster, 1, 2);
217403 Connection.Factory factory = spy(cluster.manager.connectionFactory);
@@ -219,13 +405,16 @@
219405 Connection core = pool.connections.get(0);
220406
221407 // Fill core connection + 1
222- requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
408+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
409+ assertBorrowedConnection(requests, core);
410+ allRequests.addAll(requests);
411+ allRequests.add(MockRequest.send(pool));
223412
224413 // Reaching the threshold should have triggered the creation of an extra one
225414 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
226415 assertPoolSize(pool, 2);
227416 } finally {
228- completeRequests(requests);
417+ MockRequest.completeAll(allRequests);
229418 cluster.close();
230419 }
231420 }
@@ -241,14 +430,17 @@
241430 @Test(groups = "long")
242431 public void should_resurrect_trashed_connection_within_idle_timeout() throws Exception {
243432 Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
244- List<MockRequest> requests = newArrayList();
433+ List<MockRequest> allRequests = newArrayList();
245434 try {
246435 HostConnectionPool pool = createPool(cluster, 1, 2);
247436 Connection.Factory factory = spy(cluster.manager.connectionFactory);
248437 cluster.manager.connectionFactory = factory;
249438 Connection connection1 = pool.connections.get(0);
250439
251- requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
440+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
441+ assertBorrowedConnections(requests, Collections.singletonList(connection1));
442+ allRequests.addAll(requests);
443+ allRequests.add(MockRequest.send(pool));
252444
253445 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
254446 assertPoolSize(pool, 2);
@@ -258,7 +450,7 @@
258450 assertThat(connection2.inFlight.get()).isEqualTo(0);
259451
260452 // Go back under the capacity of 1 connection
261- completeRequests(51, requests);
453+ MockRequest.completeMany(51, allRequests);
262454
263455 assertThat(connection1.inFlight.get()).isEqualTo(50);
264456 assertThat(connection2.inFlight.get()).isEqualTo(0);
@@ -269,7 +461,7 @@
269461 assertThat(pool.trash).containsExactly(connection1);
270462
271463 // Now borrow enough to go just under the 1 connection threshold
272- requests.addAll(sendRequests(50, pool));
464+ allRequests.addAll(MockRequest.sendMany(50, pool));
273465
274466 assertThat(pool.connections).containsExactly(connection2);
275467 assertThat(pool.trash).containsExactly(connection1);
@@ -277,7 +469,7 @@
277469 assertThat(connection2.inFlight.get()).isEqualTo(50);
278470
279471 // Borrowing one more time should resurrect the trashed connection
280- requests.addAll(sendRequests(1, pool));
472+ allRequests.addAll(MockRequest.sendMany(1, pool));
281473 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
282474 assertPoolSize(pool, 2);
283475
@@ -286,7 +478,7 @@
286478 assertThat(connection1.inFlight.get()).isEqualTo(50);
287479 assertThat(connection2.inFlight.get()).isEqualTo(51);
288480 } finally {
289- completeRequests(requests);
481+ MockRequest.completeAll(allRequests);
290482 cluster.close();
291483 }
292484 }
@@ -302,14 +494,17 @@
302494 @Test(groups = "long")
303495 public void should_not_resurrect_trashed_connection_after_idle_timeout() throws Exception {
304496 Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
305- List<MockRequest> requests = newArrayList();
497+ List<MockRequest> allRequests = newArrayList();
306498 try {
307499 HostConnectionPool pool = createPool(cluster, 1, 2);
308500 Connection.Factory factory = spy(cluster.manager.connectionFactory);
309501 cluster.manager.connectionFactory = factory;
310502 Connection connection1 = pool.connections.get(0);
311503
312- requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
504+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
505+ assertBorrowedConnection(requests, connection1);
506+ allRequests.addAll(requests);
507+ allRequests.add(MockRequest.send(pool));
313508
314509 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
315510 assertPoolSize(pool, 2);
@@ -320,7 +515,7 @@
320515 assertThat(connection2.inFlight.get()).isEqualTo(0);
321516
322517 // Go back under the capacity of 1 connection
323- completeRequests(51, requests);
518+ MockRequest.completeMany(51, allRequests);
324519
325520 assertThat(connection1.inFlight.get()).isEqualTo(50);
326521 assertThat(connection2.inFlight.get()).isEqualTo(0);
@@ -331,7 +526,7 @@
331526 assertThat(pool.trash).containsExactly(connection1);
332527
333528 // Return trashed connection down to 0 inFlight
334- completeRequests(50, requests);
529+ MockRequest.completeMany(50, allRequests);
335530 assertThat(connection1.inFlight.get()).isEqualTo(0);
336531
337532 // Give enough time for trashed connection to be cleaned up from the trash:
@@ -341,19 +536,22 @@
341536 assertThat(connection1.isClosed()).isTrue();
342537
343538 // Fill the live connection to go over the threshold where a second one is needed
344- requests.addAll(fillConnectionToThreshold(pool, singletonList(connection2)));
539+ requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
540+ assertBorrowedConnection(requests, connection2);
541+ allRequests.addAll(requests);
542+ allRequests.add(MockRequest.send(pool));
345543 assertThat(connection2.inFlight.get()).isEqualTo(101);
346544 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
347545 assertPoolSize(pool, 2);
348546
349547 // Borrow again to get the new connection
350548 MockRequest request = MockRequest.send(pool);
351- requests.add(request);
352- assertThat(request.connection)
549+ allRequests.add(request);
550+ assertThat(request.getConnection())
353551 .isNotEqualTo(connection2) // should not be the full connection
354552 .isNotEqualTo(connection1); // should not be the previously trashed one
355553 } finally {
356- completeRequests(requests);
554+ MockRequest.completeAll(allRequests);
357555 cluster.close();
358556 }
359557 }
@@ -368,7 +566,7 @@
368566 @Test(groups = "long")
369567 public void should_not_close_trashed_connection_until_no_in_flight() throws Exception {
370568 Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
371- List<MockRequest> requests = newArrayList();
569+ List<MockRequest> allRequests = newArrayList();
372570
373571 try {
374572 HostConnectionPool pool = createPool(cluster, 1, 2);
@@ -377,13 +575,16 @@
377575 Connection connection1 = pool.connections.get(0);
378576
379577 // Fill core connection enough to trigger creation of another one
380- requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
578+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
579+ assertBorrowedConnections(requests, Collections.singletonList(connection1));
580+ allRequests.addAll(requests);
581+ allRequests.add(MockRequest.send(pool));
381582
382583 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
383584 assertThat(pool.connections).hasSize(2);
384585
385586 // Return enough times to get back under the threshold where one connection is enough
386- completeRequests(50, requests);
587+ MockRequest.completeMany(50, allRequests);
387588
388589 // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
389590 // It still has in-flight requests so should not get closed.
@@ -393,7 +594,7 @@
393594 assertThat(connection1.isClosed()).isFalse();
394595
395596 // Consume all inFlight requests on the trashed connection.
396- completeRequests(51, requests);
597+ MockRequest.completeMany(51, allRequests);
397598
398599 // Sleep enough time for the connection to be consider idled and closed.
399600 Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS);
@@ -404,7 +605,7 @@
404605 assertThat(pool.connections).doesNotContain(connection1);
405606 assertThat(pool.trash).doesNotContain(connection1);
406607 } finally {
407- completeRequests(requests);
608+ MockRequest.completeAll(allRequests);
408609 cluster.close();
409610 }
410611 }
@@ -420,14 +621,17 @@
420621 @Test(groups = "short")
421622 public void should_trash_on_returning_connection_with_insufficient_streams() throws Exception {
422623 Cluster cluster = createClusterBuilder().build();
423- List<MockRequest> requests = newArrayList();
624+ List<MockRequest> allRequests = newArrayList();
424625 try {
425626 HostConnectionPool pool = createPool(cluster, 1, 2);
426627 Connection.Factory factory = spy(cluster.manager.connectionFactory);
427628 cluster.manager.connectionFactory = factory;
428629 Connection core = pool.connections.get(0);
429630
430- requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
631+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
632+ assertBorrowedConnections(requests, Collections.singletonList(core));
633+ allRequests.addAll(requests);
634+ allRequests.add(MockRequest.send(pool));
431635
432636 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
433637 assertThat(pool.connections).hasSize(2);
@@ -437,7 +641,7 @@
437641 pool.connections.set(1, extra1);
438642
439643 // Borrow 10 times to ensure pool is utilized.
440- requests.addAll(sendRequests(10, pool));
644+ allRequests.addAll(MockRequest.sendMany(10, pool));
441645 assertThat(pool.connections).hasSize(2);
442646
443647 // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
@@ -449,7 +653,7 @@
449653 pool.returnConnection(extra1);
450654 assertThat(pool.trash).hasSize(1);
451655 } finally {
452- completeRequests(requests);
656+ MockRequest.completeAll(allRequests);
453657 cluster.close();
454658 }
455659 }
@@ -486,7 +690,6 @@
486690 }
487691 }
488692
489-
490693 /**
491694 * Ensures that if all connections on a host are closed that the host is marked
492695 * down and the control connection is notified of that fact and re-established
@@ -561,7 +764,6 @@
561764 }
562765 }
563766
564-
565767 /**
566768 * Ensures that if a connection on a host is lost that brings the number of active connections in a pool
567769 * under core connection count that up to core connections are re-established, but only after the
@@ -580,7 +782,7 @@
580782 .setConnectTimeoutMillis(readTimeout)
581783 .setReadTimeoutMillis(reconnectInterval))
582784 .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
583- List<MockRequest> requests = newArrayList();
785+ List<MockRequest> allRequests = newArrayList();
584786 try {
585787 cluster.init();
586788
@@ -608,8 +810,8 @@
608810
609811 // The borrowed connection should be the open one.
610812 MockRequest request = MockRequest.send(pool);
611- requests.add(request);
612- assertThat(request.connection).isEqualTo(core1);
813+ allRequests.add(request);
814+ assertThat(request.getConnection()).isEqualTo(core1);
613815
614816 // Should not have tried to create a new core connection since reconnection time had not elapsed.
615817 verify(factory, never()).open(any(HostConnectionPool.class));
@@ -620,8 +822,8 @@
620822 // Attempt to borrow connection, this should trigger ensureCoreConnections thus spawning a new connection.
621823 blockingExecutor.reset();
622824 request = MockRequest.send(pool);
623- requests.add(request);
624- assertThat(request.connection).isEqualTo(core1);
825+ allRequests.add(request);
826+ assertThat(request.getConnection()).isEqualTo(core1);
625827
626828 // Should have tried to open up to core connections as result of borrowing a connection past reconnect time and not being at core.
627829 blockingExecutor.blockUntilNextTaskCompleted();
@@ -638,23 +840,23 @@
638840
639841 // Try to borrow a connection, the pool should grow.
640842 blockingExecutor.reset();
641- requests.add(MockRequest.send(pool));
843+ allRequests.add(MockRequest.send(pool));
642844 blockingExecutor.blockUntilNextTaskCompleted();
643845 verify(factory).open(any(HostConnectionPool.class));
644846 reset(factory);
645847
646848 // Another core connection should be opened as result of another request to get us up to core connections.
647849 blockingExecutor.reset();
648- requests.add(MockRequest.send(pool));
850+ allRequests.add(MockRequest.send(pool));
649851 blockingExecutor.blockUntilNextTaskCompleted();
650852 verify(factory).open(any(HostConnectionPool.class));
651853 reset(factory);
652854
653855 // Sending another request should not grow the pool any more, since we are now at core connections.
654- requests.add(MockRequest.send(pool));
856+ allRequests.add(MockRequest.send(pool));
655857 verify(factory, after((reconnectInterval + readTimeout) * 2).never()).open(any(HostConnectionPool.class));
656858 } finally {
657- completeRequests(requests);
859+ MockRequest.completeAll(allRequests);
658860 cluster.close();
659861 }
660862 }
@@ -677,7 +879,7 @@
677879 .setConnectTimeoutMillis(readTimeout)
678880 .setReadTimeoutMillis(reconnectInterval))
679881 .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
680- List<MockRequest> requests = newArrayList();
882+ List<MockRequest> allRequests = newArrayList();
681883 try {
682884 cluster.init();
683885
@@ -691,7 +893,7 @@
691893 List<MockRequest> core0requests = newArrayList();
692894 for (int i = 0; i < 101; i++) {
693895 MockRequest request = MockRequest.send(pool);
694- assertThat(request.connection).isEqualTo(core0);
896+ assertThat(request.getConnection()).isEqualTo(core0);
695897 core0requests.add(request);
696898 }
697899
@@ -712,13 +914,15 @@
712914
713915 // Since core0 was closed, all of it's requests should have errored.
714916 for (MockRequest request : core0requests) {
715- verify(request, times(1)).onException(any(Connection.class), any(Exception.class), anyLong(), anyInt());
917+ assertThat(request.state.get()).isEqualTo(MockRequest.State.FAILED);
716918 }
717919
718920 assertThat(cluster).host(1).hasState(Host.State.UP);
719921
720922 // Create enough inFlight requests to fill connection.
721- requests.addAll(sendRequests(100, pool, singletonList(extra1)));
923+ List<MockRequest> requests = MockRequest.sendMany(100, pool);
924+ assertBorrowedConnections(requests, Collections.singletonList(extra1));
925+ allRequests.addAll(requests);
722926 assertThat(pool.connections).hasSize(1);
723927
724928 // A new connection should never have been spawned since we didn't max out core.
@@ -726,8 +930,8 @@
726930
727931 // Borrow another connection, since we exceed max another connection should be opened.
728932 MockRequest request = MockRequest.send(pool);
729- requests.add(request);
730- assertThat(request.connection).isEqualTo(extra1);
933+ allRequests.add(request);
934+ assertThat(request.getConnection()).isEqualTo(extra1);
731935
732936 // After some time the a connection should attempt to be opened (but will fail).
733937 verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
@@ -745,8 +949,8 @@
745949
746950 // Borrow another connection, since we exceed max another connection should be opened.
747951 request = MockRequest.send(pool);
748- requests.add(request);
749- assertThat(request.connection).isEqualTo(extra1);
952+ allRequests.add(request);
953+ assertThat(request.getConnection()).isEqualTo(extra1);
750954
751955 // Wait some reasonable amount of time for connection to reestablish then check pool size.
752956 Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
@@ -755,10 +959,10 @@
755959
756960 // Borrowed connection should be the newly spawned connection since the other one has some inflight requests.
757961 request = MockRequest.send(pool);
758- requests.add(request);
759- assertThat(request.connection).isNotEqualTo(core0).isNotEqualTo(extra1);
962+ allRequests.add(request);
963+ assertThat(request.getConnection()).isNotEqualTo(core0).isNotEqualTo(extra1);
760964 } finally {
761- completeRequests(requests);
965+ MockRequest.completeAll(allRequests);
762966 cluster.close();
763967 }
764968 }
@@ -781,7 +985,7 @@
781985 .setConnectTimeoutMillis(readTimeout)
782986 .setReadTimeoutMillis(reconnectInterval))
783987 .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
784- List<MockRequest> requests = newArrayList();
988+ List<MockRequest> allRequests = newArrayList();
785989 try {
786990 cluster.init();
787991
@@ -811,13 +1015,13 @@
8111015 // we need to wait for connections to be established between requests for the pool
8121016 // to spawn new connections (since it only allows one simultaneous creation).
8131017 for (int i = 5; i <= 8; i++) {
814- requests.add(MockRequest.send(pool));
1018+ allRequests.add(MockRequest.send(pool));
8151019 verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
8161020 reset(factory);
8171021 assertPoolSize(pool, i);
8181022 }
8191023 } finally {
820- completeRequests(requests);
1024+ MockRequest.completeAll(allRequests);
8211025 cluster.close();
8221026 }
8231027 }
@@ -825,15 +1029,15 @@
8251029 /**
8261030 * Ensures that if all connections fail on pool init that the host and subsequently the
8271031 * control connection is not marked down since the control connection is still active.
828- * on the pool that a TimeoutException is yielded if we are still in the reconnection window
1032+ * The test also ensures that borrow attempts on the pool fail if we are still in the reconnection window
8291033 * according to the ConvictionPolicy.
8301034 *
8311035 * @jira_ticket JAVA-544
8321036 * @test_category connection:connection_pool
8331037 * @since 2.0.11
8341038 */
835- @Test(groups = "short", expectedExceptions = TimeoutException.class)
836- public void should_throw_exception_if_convicted_and_no_connections_available() throws Exception {
1039+ @Test(groups = "short")
1040+ public void should_throw_exception_if_convicted_and_no_connections_available() {
8371041 int readTimeout = 1000;
8381042 int reconnectInterval = 1000;
8391043 Cluster cluster = this.createClusterBuilder()
@@ -862,16 +1066,19 @@
8621066 assertThat(cluster).host(1).hasState(Host.State.UP);
8631067 assertThat(cluster).hasOpenControlConnection();
8641068
865- MockRequest.send(pool);
1069+ MockRequest failedBorrow = MockRequest.send(pool);
1070+ try {
1071+ failedBorrow.getConnection();
1072+ fail("Expected a BusyPoolException");
1073+ } catch (BusyPoolException e) { /*expected*/}
8661074 } finally {
8671075 cluster.close();
8681076 }
8691077 }
8701078
871-
8721079 /**
8731080 * Ensures that if all connections fail on pool init that the host and subsequently the
874- * control connection is not marked down. The test also ensures that when making requests
1081+ * control connection is not marked down. The test also ensures that when making requests
8751082 * on the pool after the conviction period that all core connections are created.
8761083 *
8771084 * @jira_ticket JAVA-544
@@ -912,12 +1119,13 @@
9121119 Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
9131120
9141121 reset(factory);
915- MockRequest request = MockRequest.send(pool);
916- request.simulateSuccessResponse();
1122+ MockRequest request = MockRequest.send(pool, 1);
9171123
9181124 // Should create up to core connections.
9191125 verify(factory, timeout(readTimeout * 8).times(8)).open(any(HostConnectionPool.class));
9201126 assertPoolSize(pool, 8);
1127+
1128+ request.simulateSuccessResponse();
9211129 } finally {
9221130 cluster.close();
9231131 }
@@ -946,6 +1154,9 @@
9461154 cluster.init();
9471155 assertThat(cluster).hasOpenControlConnection();
9481156
1157+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
1158+ cluster.manager.connectionFactory = factory;
1159+
9491160 HostConnectionPool pool = createPool(cluster, 0, 2);
9501161
9511162 // Pool should be empty.
@@ -955,12 +1166,14 @@
9551166 assertThat(cluster).host(1).hasState(Host.State.UP);
9561167 assertThat(cluster).hasOpenControlConnection();
9571168
958- // Send a request, this should create a connection.
959- MockRequest request = MockRequest.send(pool);
960- request.simulateSuccessResponse();
1169+ reset(factory);
1170+ MockRequest request = MockRequest.send(pool, 1);
9611171
9621172 // Should create up to core connections.
1173+ verify(factory, timeout(readTimeout).times(1)).open(any(HostConnectionPool.class));
9631174 assertThat(pool.connections).hasSize(1);
1175+
1176+ request.simulateSuccessResponse();
9641177 } finally {
9651178 cluster.close();
9661179 }
@@ -979,10 +1192,10 @@
9791192 }
9801193
9811194 /**
982- * <p>
1195+ * <p/>
9831196 * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the
9841197 * insertions are being executed, the number of opened connection is monitored.
985- * <p>
1198+ * <p/>
9861199 * If at anytime, the number of opened connections is negative, this test will fail.
9871200 *
9881201 * @jira_ticket JAVA-349
@@ -1061,51 +1274,115 @@
10611274
10621275 enum State {START, COMPLETED, FAILED, TIMED_OUT}
10631276
1064- final Connection connection;
1065- private Connection.ResponseHandler responseHandler;
1277+ final ListenableFuture<Connection> connectionFuture;
1278+ private volatile Connection.ResponseHandler responseHandler;
1279+
1280+ final AtomicReference<State> state = new AtomicReference<State>(State.START);
1281+
1282+ static MockRequest send(HostConnectionPool pool) {
1283+ return send(pool, 0);
1284+ }
1285+
1286+ static MockRequest send(HostConnectionPool pool, int maxQueueSize) throws ConnectionException, BusyConnectionException {
1287+ return new MockRequest(pool, maxQueueSize);
1288+ }
1289+
1290+ private static List<MockRequest> sendMany(int count, HostConnectionPool pool) throws ConnectionException {
1291+ return sendMany(count, pool, 0);
1292+ }
1293+
1294+ private static List<MockRequest> sendMany(int count, HostConnectionPool pool, int maxQueueSize) throws ConnectionException {
1295+ List<MockRequest> requests = newArrayList();
1296+ for (int i = 0; i < count; i++) {
1297+ MockRequest request = send(pool, maxQueueSize);
1298+ requests.add(request);
1299+ }
1300+ return requests;
1301+ }
10661302
1067- private final AtomicReference<State> state = new AtomicReference<State>(State.START);
1303+ /**
1304+ * Completes count requests by simulating a successful response.
1305+ */
1306+ private static void completeMany(int count, List<MockRequest> requests) {
1307+ Iterator<MockRequest> requestIt = requests.iterator();
1308+ for (int i = 0; i < count; i++) {
1309+ if (requestIt.hasNext()) {
1310+ MockRequest request = requestIt.next();
1311+ request.simulateSuccessResponse();
1312+ requestIt.remove();
1313+ } else {
1314+ break;
1315+ }
1316+ }
1317+ }
10681318
1069- static MockRequest send(HostConnectionPool pool) throws ConnectionException, BusyConnectionException, TimeoutException {
1070- // Create a MockRequest and spy on it. Create a response handler and add it to the connection's dispatcher.
1071- MockRequest request = spy(new MockRequest(pool));
1072- request.responseHandler = new Connection.ResponseHandler(request.connection, -1, request);
1073- request.connection.dispatcher.add(request.responseHandler);
1074- return request;
1319+ /**
1320+ * Completes all requests by simulating a successful response.
1321+ */
1322+ private static void completeAll(List<MockRequest> requests) {
1323+ for (MockRequest request : requests) {
1324+ request.simulateSuccessResponse();
1325+ }
10751326 }
10761327
1077- private MockRequest(HostConnectionPool pool) throws ConnectionException, TimeoutException, BusyConnectionException {
1078- connection = pool.borrowConnection(500, TimeUnit.MILLISECONDS);
1328+ private MockRequest(HostConnectionPool pool, int maxQueueSize) throws ConnectionException {
1329+ this.connectionFuture = pool.borrowConnection(maxQueueSize);
1330+ Futures.addCallback(this.connectionFuture, new MoreFutures.SuccessCallback<Connection>() {
1331+ @Override
1332+ public void onSuccess(Connection connection) {
1333+ MockRequest thisRequest = MockRequest.this;
1334+ thisRequest.responseHandler = new Connection.ResponseHandler(connection, -1, thisRequest);
1335+ connection.dispatcher.add(thisRequest.responseHandler);
1336+ }
1337+ });
10791338 }
10801339
10811340 void simulateSuccessResponse() {
1082- onSet(connection, null, 0, 0);
1341+ onSet(getConnection(), null, 0, 0);
10831342 }
10841343
10851344 @SuppressWarnings("unused")
10861345 void simulateErrorResponse() {
1087- onException(connection, null, 0, 0);
1346+ onException(getConnection(), null, 0, 0);
10881347 }
10891348
10901349 @SuppressWarnings("unused")
10911350 void simulateTimeout() {
1092- if (onTimeout(connection, 0, 0))
1351+ if (onTimeout(getConnection(), 0, 0))
10931352 responseHandler.cancelHandler();
10941353 }
10951354
1355+ // Get the connection, assuming pool acquisition completed
1356+ Connection getConnection() {
1357+ try {
1358+ if (!connectionFuture.isDone()) {
1359+ throw new AssertionError("Borrow call did not complete");
1360+ }
1361+ return Uninterruptibles.getUninterruptibly(connectionFuture);
1362+ } catch (ExecutionException e) {
1363+ throw Throwables.propagate(e.getCause());
1364+ }
1365+ }
1366+
10961367 @Override
10971368 public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
1369+ assertThat(connectionFuture.isDone()).isTrue();
1370+ try {
1371+ assertThat(Uninterruptibles.getUninterruptibly(connectionFuture)).isNotNull();
1372+ } catch (ExecutionException e) {
1373+ Throwables.propagate(e.getCause());
1374+ }
10981375 if (state.compareAndSet(State.START, State.COMPLETED)) {
1099- connection.release();
11001376 connection.dispatcher.removeHandler(responseHandler, true);
1377+ connection.release();
11011378 }
11021379 }
11031380
11041381 @Override
11051382 public void onException(Connection connection, Exception exception, long latency, int retryCount) {
11061383 if (state.compareAndSet(State.START, State.FAILED)) {
1107- connection.release();
11081384 connection.dispatcher.removeHandler(responseHandler, true);
1385+ connection.release();
11091386 }
11101387 }
11111388
modified manual/async/README.md +0 −12
@@ -130,21 +130,9 @@
130130 issues, you should create your `Cluster` instances while bootstrapping
131131 your application, and call `init` immediately. If you need to create new
132132 instances at runtime, make sure this does not happen on an I/O thread.
133-* if a connection pool is busy, the driver will block until a connection
134- becomes available. To avoid this, set
135- [PoolingOptions.poolTimeoutMillis][setPoolTimeoutMillis] to 0; the
136- driver will not block, just move to the next host immediately.
137-* if the session is set to a specific keyspace (either at startup or by
138- issuing a `USE` statement on a running session), the keyspace needs to
139- be propagated to any newly created connection. This is done when the
140- connection is first borrowed from the connection pool, and currently
141- blocks. To avoid any issue, only use a session with no keyspace set
142- (i.e. created by `Cluster#connect()`). This will be addressed in
143- [JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893).
144133 * trying to read fields from a [query trace] will block if the trace
145134 hasn't been fetched already.
146135
147136 [ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained
148137 [init]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Cluster.html#init--
149-[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis-int-
150138 [query trace]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryTrace.html
modified manual/pooling/README.md +24 −23
@@ -180,24 +180,24 @@
180180 message.
181181
182182
183-#### Acquisition timeout
183+#### Acquisition queue
184184
185185 When the driver tries to send a request to a host, it will first try to
186186 acquire a connection from this host's pool. If the pool is busy (i.e.
187187 all connections are already handling their maximum number of in flight
188-requests), the client thread will block for a while, until a connection
189-becomes available (note that this will block even if you're using the
190-asynchronous API, like [Session.executeAsync][exec_async]).
188+requests), the acquisition attempt gets enqueued until a connection becomes
189+available again.
191190
192-The time that the driver blocks is controlled by
193-[PoolingOptions.setPoolTimeoutMillis][ptm]. If there is still no connection
194-available after this timeout, the driver will try the next host.
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.
195196
196-For some applications, blocking is not acceptable, and it is preferable
197-to fail fast if the request cannot be fulfilled. If that's your case,
198-set the pool timeout to 0. If all hosts are busy, you will get a
199-[NoHostAvailableException][nhae] (if you look at the exception's details, you
200-will see a `java.util.concurrent.TimeoutException` for each host).
197+If all hosts are busy with a full queue, the request will fail with a
198+[NoHostAvailableException][nhae]. If you inspect the map returns by this
199+exception's [getErrors] method, you will see a [BusyPoolException] for
200+each host.
201201
202202
203203 ### Monitoring and tuning the pool
@@ -278,14 +278,15 @@
278278 [newConnectionThreshold][nct] so that enough connections are added by
279279 the time you reach the bottleneck.
280280
281-[result_set_future]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSetFuture.html
282-[pooling_options]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html
283-[lbp]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
284-[nct]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold-com.datastax.driver.core.HostDistance-int-
285-[mrpc]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection-com.datastax.driver.core.HostDistance-int-
286-[sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int-
287-[rtm]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis--
288-[exec_async]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement-
289-[ptm]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis-int-
290-[nhae]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
291-[get_state]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#getState--
281+[result_set_future]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSetFuture.html
282+[pooling_options]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html
283+[lbp]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
284+[nct]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold-com.datastax.driver.core.HostDistance-int-
285+[mrpc]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection-com.datastax.driver.core.HostDistance-int-
286+[sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int-
287+[rtm]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis--
288+[smqs]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxQueueSize-int-
289+[nhae]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html
290+[getErrors]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html#getErrors--
291+[get_state]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#getState--
292+[BusyPoolException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/BusyPoolException.html
modified upgrade_guide/README.md +16 −0
@@ -3,6 +3,22 @@
33 The purpose of this guide is to detail changes made by successive
44 versions of the Java driver.
55
6+### 3.0.4
7+
8+The connection pool is now fully non-blocking ([JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893)),
9+which greatly improves asynchronous programming:
10+
11+* `Session.executeAsync` won't ever block the user thread anymore;
12+* you can now safely run async queries on a session connected to a keyspace.
13+
14+This new implementation brings a couple of changes:
15+
16+* pool saturation is no longer handled by a timeout, but instead by a bounded queue. As a consequence,
17+ `PoolingOptions.setPoolTimeoutMillis` has been deprecated, and replaced by `setMaxQueueSize`;
18+* a saturated pool will now throw `BusyPoolException` instead of `TimeoutException` (note that this exception is not
19+ rethrown directly to the client, but wrapped in `NoHostAvailableException.getErrors()`).
20+
21+
622 ### 3.0.0
723
824 This version brings parity with Cassandra 2.2 and 3.0.