Elffuss BraidHub

kikocis/java-driver public

JAVA-893: Make connection pool non-blocking
Changeseted90b7b4a2f8918beb1837f4547c7419fdc4de3e452fa6e99b26e5abb3a1c81c
Authorolim7t <omichallat+github@gmail.com> · 2016-09-02 11:18 -07:00
Committerolim7t <omichallat+github@gmail.com> · 2016-09-23 22:41 -07:00
Parentsda9ef71e7257

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 +13 −5
@@ -19,6 +19,8 @@
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.Function;
23+import com.google.common.base.Objects;
2224 import com.google.common.collect.Lists;
2325 import com.google.common.collect.MapMaker;
2426 import com.google.common.util.concurrent.*;
@@ -95,8 +97,9 @@
9597
9698 private final AtomicReference<Owner> ownerRef = new AtomicReference<Owner>();
9799
100+ private final ListenableFuture<Connection> thisFuture;
101+
98102 /**
99- * /**
100103 * Create a new connection to a Cassandra node and associate it with the given pool.
101104 *
102105 * @param name the connection name
@@ -111,6 +114,7 @@
111114 this.dispatcher = new Dispatcher();
112115 this.name = name;
113116 this.ownerRef.set(owner);
117+ this.thisFuture = Futures.immediateFuture(this);
114118 }
115119
116120 /**
@@ -483,16 +487,20 @@
483487 }
484488 }
485489
486- ListenableFuture<Void> setKeyspaceAsync(final String keyspace) throws ConnectionException, BusyConnectionException {
490+ ListenableFuture<Connection> setKeyspaceAsync(final String keyspace) throws ConnectionException, BusyConnectionException {
491+ if (Objects.equal(this.keyspace, keyspace)) {
492+ return thisFuture;
493+ }
494+
487495 logger.trace("{} Setting keyspace {}", this, keyspace);
488496 // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already
489497 Future future = write(new Requests.Query("USE \"" + keyspace + '"'));
490- return Futures.transform(future, new AsyncFunction<Message.Response, Void>() {
498+ return Futures.transform(future, new Function<Message.Response, Connection>() {
491499 @Override
492- public ListenableFuture<Void> apply(Message.Response response) throws Exception {
500+ public Connection apply(Message.Response response) {
493501 if (response instanceof SetKeyspace) {
494502 Connection.this.keyspace = ((SetKeyspace) response).keyspace;
495- return MoreFutures.VOID_SUCCESS;
503+ return Connection.this;
496504 } else if (response.type == ERROR) {
497505 Responses.Error error = (Responses.Error) response;
498506 throw defunct(error.asException(address));
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +75 −114
@@ -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,13 @@
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;
33-import java.util.concurrent.*;
30+import java.util.*;
31+import java.util.concurrent.ConcurrentLinkedQueue;
32+import java.util.concurrent.CopyOnWriteArrayList;
33+import java.util.concurrent.CopyOnWriteArraySet;
34+import java.util.concurrent.Executor;
3435 import java.util.concurrent.atomic.AtomicInteger;
3536 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;
3937
4038 import static com.datastax.driver.core.Connection.State.*;
4139
@@ -62,9 +60,8 @@
6260 @VisibleForTesting
6361 final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
6462
65- private volatile int waiter = 0;
66- private final Lock waitLock = new ReentrantLock(true);
67- private final Condition hasAvailableConnection = waitLock.newCondition();
63+ private final Queue<SettableFuture<Connection>> pendingBorrows = new ConcurrentLinkedQueue<SettableFuture<Connection>>();
64+ private final AtomicInteger pendingBorrowCount = new AtomicInteger();
6865
6966 private final Runnable newConnectionTask;
7067
@@ -81,7 +78,7 @@
8178 // following threshold, we just replace the connection by a new one.
8279 private final int minAllowedStreams;
8380
84- public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
81+ HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
8582 assert hostDistance != HostDistance.IGNORED;
8683 this.host = host;
8784 this.hostDistance = hostDistance;
@@ -196,17 +193,13 @@
196193 return manager.configuration().getPoolingOptions();
197194 }
198195
199- public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
196+ ListenableFuture<Connection> borrowConnection(int maxQueueSize) {
200197 Phase phase = this.phase.get();
201198 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);
199+ return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is " + phase));
205200
206201 if (connections.isEmpty()) {
207- if (!host.convictionPolicy.canReconnectNow())
208- throw new TimeoutException("Connection pool is empty, currently trying to reestablish connections");
209- else {
202+ if (host.convictionPolicy.canReconnectNow()) {
210203 int coreSize = options().getCoreConnectionsPerHost(hostDistance);
211204 if (coreSize == 0) {
212205 maybeSpawnNewConnection();
@@ -218,10 +211,7 @@
218211 manager.blockingExecutor().submit(newConnectionTask);
219212 }
220213 }
221- Connection c = waitForConnection(timeout, unit);
222- totalInFlight.incrementAndGet();
223- c.setKeyspace(manager.poolsState.keyspace);
224- return c;
214+ return enqueue(maxQueueSize);
225215 }
226216 }
227217
@@ -238,18 +228,17 @@
238228 if (leastBusy == null) {
239229 // We could have raced with a shutdown since the last check
240230 if (isClosed())
241- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
231+ return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
242232 // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between
243233 // the previous check to connections and now. But in that case, the line above will have trigger the creation of
244234 // a new connection, so just wait that connection and move on
245- leastBusy = waitForConnection(timeout, unit);
235+ return enqueue(maxQueueSize);
246236 } else {
247237 while (true) {
248238 int inFlight = leastBusy.inFlight.get();
249239
250240 if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) {
251- leastBusy = waitForConnection(timeout, unit);
252- break;
241+ return enqueue(maxQueueSize);
253242 }
254243
255244 if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
@@ -276,96 +265,37 @@
276265 maybeSpawnNewConnection();
277266 }
278267
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- }
268+ return leastBusy.setKeyspaceAsync(manager.poolsState.keyspace);
305269 }
306270
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();
271+ private ListenableFuture<Connection> enqueue(int maxQueueSize) {
272+ if (maxQueueSize == 0) {
273+ return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), 0));
317274 }
318- }
319275
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
276+ while (true) {
277+ int count = pendingBorrowCount.get();
278+ if (count >= maxQueueSize) {
279+ return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), maxQueueSize));
333280 }
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- }
281+ if (pendingBorrowCount.compareAndSet(count, count + 1)) {
282+ break;
346283 }
284+ }
347285
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- }
286+ SettableFuture<Connection> future = SettableFuture.create();
287+ pendingBorrows.add(future);
361288
362- remaining = timeout - Cluster.timeSince(start, unit);
363- } while (remaining > 0);
289+ // If we raced with shutdown, make sure the future will be completed. This has no effect if it was properly
290+ // handled in closeAsync.
291+ if (phase.get() == Phase.CLOSING) {
292+ future.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
293+ }
364294
365- throw new TimeoutException("All connections are busy");
295+ return future;
366296 }
367297
368- public void returnConnection(Connection connection) {
298+ void returnConnection(Connection connection) {
369299 connection.inFlight.decrementAndGet();
370300 totalInFlight.decrementAndGet();
371301
@@ -384,7 +314,37 @@
384314 if (connection.maxAvailableStreams() < minAllowedStreams) {
385315 replaceConnection(connection);
386316 } else {
387- signalAvailableConnection();
317+ dequeue(connection);
318+ }
319+ }
320+ }
321+
322+ // When a connection gets returned to the pool, check if there are pending borrows that can be completed with it.
323+ private void dequeue(Connection connection) {
324+ while (!pendingBorrows.isEmpty()) {
325+
326+ // We can only reuse the connection if it's under its maximum number of inFlight requests.
327+ // Do this atomically, as we could be competing with other borrowConnection or dequeue calls.
328+ while (true) {
329+ int inFlight = connection.inFlight.get();
330+ if (inFlight >= Math.min(connection.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) {
331+ // Connection is full again, stop dequeuing
332+ return;
333+ }
334+ if (connection.inFlight.compareAndSet(inFlight, inFlight + 1)) {
335+ // We acquired the right to reuse the connection for one request, proceed
336+ break;
337+ }
338+ }
339+
340+ SettableFuture<Connection> pendingBorrow = pendingBorrows.poll();
341+ if (pendingBorrow == null) {
342+ // Another thread has emptied the queue since our last check, restore the count
343+ connection.inFlight.decrementAndGet();
344+ } else {
345+ totalInFlight.incrementAndGet();
346+ pendingBorrowCount.decrementAndGet();
347+ pendingBorrow.set(connection);
388348 }
389349 }
390350 }
@@ -465,7 +425,7 @@
465425 return false;
466426 }
467427
468- signalAvailableConnection();
428+ dequeue(newConnection);
469429 return true;
470430 } catch (InterruptedException e) {
471431 Thread.currentThread().interrupt();
@@ -600,11 +560,11 @@
600560 connection.closeAsync();
601561 }
602562
603- public final boolean isClosed() {
563+ final boolean isClosed() {
604564 return closeFuture.get() != null;
605565 }
606566
607- public final CloseFuture closeAsync() {
567+ final CloseFuture closeAsync() {
608568
609569 CloseFuture future = closeFuture.get();
610570 if (future != null)
@@ -612,8 +572,9 @@
612572
613573 phase.set(Phase.CLOSING);
614574
615- // Wake up all threads that wait
616- signalAllAvailableConnection();
575+ for (SettableFuture<Connection> pendingBorrow : pendingBorrows) {
576+ pendingBorrow.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown"));
577+ }
617578
618579 future = new CloseFuture.Forwarding(discardAvailableConnections());
619580
@@ -622,7 +583,7 @@
622583 : closeFuture.get(); // We raced, it's ok, return the future that was actually set
623584 }
624585
625- public int opened() {
586+ int opened() {
626587 return open.get();
627588 }
628589
@@ -657,7 +618,7 @@
657618
658619 // This creates connections if we have less than core connections (if we
659620 // have more than core, connection will just get trash when we can).
660- public void ensureCoreConnections() {
621+ void ensureCoreConnections() {
661622 if (isClosed())
662623 return;
663624
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 +217 −153
@@ -19,7 +19,9 @@
1919 import com.datastax.driver.core.exceptions.BusyConnectionException;
2020 import com.datastax.driver.core.exceptions.ConnectionException;
2121 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
22+import com.datastax.driver.core.utils.MoreFutures;
2223 import com.google.common.base.Predicate;
24+import com.google.common.base.Throwables;
2325 import com.google.common.util.concurrent.*;
2426 import org.scassandra.cql.PrimitiveType;
2527 import org.scassandra.http.client.PrimingRequest;
@@ -27,6 +29,7 @@
2729 import org.testng.annotations.Test;
2830
2931 import java.net.InetSocketAddress;
32+import java.util.Collections;
3033 import java.util.Iterator;
3134 import java.util.List;
3235 import java.util.concurrent.*;
@@ -35,8 +38,8 @@
3538
3639 import static com.datastax.driver.core.Assertions.assertThat;
3740 import static com.datastax.driver.core.ConditionChecker.check;
41+import static com.datastax.driver.core.PoolingOptions.NEW_CONNECTION_THRESHOLD_LOCAL_KEY;
3842 import static com.google.common.collect.Lists.newArrayList;
39-import static java.util.Collections.singletonList;
4043 import static java.util.concurrent.TimeUnit.SECONDS;
4144 import static org.mockito.Mockito.*;
4245 import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE;
@@ -45,6 +48,9 @@
4548
4649 public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster {
4750
51+ static final Integer NEW_CONNECTION_THRESHOLD = PoolingOptions.DEFAULTS.get(ProtocolVersion.V1)
52+ .get(NEW_CONNECTION_THRESHOLD_LOCAL_KEY);
53+
4854 @BeforeClass(groups = {"short", "long"})
4955 public void reinitializeCluster() {
5056 // Don't use the provided cluster, each test will create its own instead.
@@ -67,93 +73,56 @@
6773 }).becomesTrue();
6874 }
6975
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;
77- }
78-
79- /**
80- * Sends count requests on pool.
81- */
82- private List<MockRequest> sendRequests(int count, HostConnectionPool pool) throws ConnectionException, BusyConnectionException, TimeoutException {
83- return sendRequests(count, pool, null);
84- }
85-
86- /**
87- * Sends count requests on pool, asserting that the connection used is in expectedConnections.
88- */
89- private List<MockRequest> sendRequests(int count, HostConnectionPool pool, List<Connection> expectedConnections) throws ConnectionException, BusyConnectionException, TimeoutException {
90- 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;
98- }
99-
100- /**
101- * Completes count requests by simulating a successful response.
102- */
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;
112- }
76+ private void assertBorrowedConnections(Iterable<MockRequest> requests, List<Connection> expectedConnections) {
77+ for (MockRequest request : requests) {
78+ assertThat(expectedConnections).contains(request.getConnection());
11379 }
11480 }
11581
116- /**
117- * Completes all requests by simulating a successful response.
118- */
119- private void completeRequests(List<MockRequest> requests) {
120- for (MockRequest request : requests) {
121- request.simulateSuccessResponse();
122- }
82+ private void assertBorrowedConnection(Iterable<MockRequest> requests, Connection expectedConnection) {
83+ assertBorrowedConnections(requests, Collections.singletonList(expectedConnection));
12384 }
12485
12586 /**
126- * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead
127- * of creating a new connection.
87+ * Ensures that if a fixed-sized pool has filled its core connections and reached its maximum number of enqueued
88+ * requests, then borrowConnection will fail instead of creating a new connection.
12889 *
12990 * @jira_ticket JAVA-419
13091 * @test_category connection:connection_pool
13192 * @since 2.0.10, 2.1.6
13293 */
13394 @Test(groups = "short")
134- public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException, BusyConnectionException {
95+ public void fixed_size_pool_should_fill_its_core_connections_and_queue_and_then_reject() {
13596 Cluster cluster = createClusterBuilder().build();
136- List<MockRequest> requests = newArrayList();
97+ List<MockRequest> allRequests = newArrayList();
13798 try {
13899 HostConnectionPool pool = createPool(cluster, 2, 2);
100+ int maxQueueSize = 256;
139101
140102 assertThat(pool.connections.size()).isEqualTo(2);
141103 List<Connection> coreConnections = newArrayList(pool.connections);
142- requests.addAll(sendRequests(256, pool, coreConnections));
143-
104+ // fill connections
105+ List<MockRequest> requests = MockRequest.sendMany(2 * 128, pool);
106+ assertBorrowedConnections(requests, coreConnections);
107+ allRequests.addAll(requests);
108+ // fill queue
109+ allRequests.addAll(MockRequest.sendMany(maxQueueSize, pool, maxQueueSize));
110+
111+ // add one more request, it should be rejected because the queue is full
112+ MockRequest failedBorrow = MockRequest.send(pool, maxQueueSize);
144113 try {
145- MockRequest.send(pool);
146- Assertions.fail("Expected a TimeoutException");
147- } catch (TimeoutException e) { /*expected*/}
114+ failedBorrow.getConnection();
115+ fail("Expected a ConnectionException");
116+ } catch (ConnectionException e) { /*expected*/}
148117 } finally {
149- completeRequests(requests);
118+ MockRequest.completeAll(allRequests);
150119 cluster.close();
151120 }
152121 }
153122
154123 /**
155124 * 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.
125+ * return a failed future instead of creating a new connection.
157126 *
158127 * @jira_ticket JAVA-419
159128 * @test_category connection:connection_pool
@@ -162,41 +131,42 @@
162131 @Test(groups = "short")
163132 public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws Exception {
164133 Cluster cluster = createClusterBuilder().build();
165- List<MockRequest> requests = newArrayList();
134+ List<MockRequest> allRequests = newArrayList();
166135 try {
167136 HostConnectionPool pool = createPool(cluster, 1, 2);
168137 Connection.Factory factory = spy(cluster.manager.connectionFactory);
169138 cluster.manager.connectionFactory = factory;
170139
171140 assertThat(pool.connections.size()).isEqualTo(1);
172- List<Connection> coreConnections = newArrayList(pool.connections);
141+ Connection coreConnection = pool.connections.get(0);
173142
174143 // Fill enough connections to hit the threshold.
175- requests.addAll(fillConnectionToThreshold(pool, coreConnections));
144+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
145+ assertBorrowedConnection(requests, coreConnection);
146+ allRequests.addAll(requests);
147+ allRequests.add(MockRequest.send(pool));
176148
177149 // Allow time for new connection to be spawned.
178150 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
179151 assertPoolSize(pool, 2);
180152
181153 // Borrow more and ensure the connection returned is a non-core connection.
182- for (int i = 0; i < 100; i++) {
154+ for (int i = 0; i < NEW_CONNECTION_THRESHOLD; i++) {
183155 MockRequest request = MockRequest.send(pool);
184- assertThat(coreConnections).doesNotContain(request.connection);
185- requests.add(request);
156+ assertThat(request.getConnection()).isNotEqualTo(coreConnection);
157+ allRequests.add(request);
186158 }
187159
188160 // Fill remaining connections (28 + 28) - 1
189- requests.addAll(sendRequests(55, pool));
161+ allRequests.addAll(MockRequest.sendMany(55, pool));
190162
191- boolean timedOut = false;
163+ MockRequest failedBorrow = MockRequest.send(pool);
192164 try {
193- MockRequest.send(pool);
194- } catch (TimeoutException e) {
195- timedOut = true;
196- }
197- assertThat(timedOut).isTrue();
165+ failedBorrow.getConnection();
166+ fail("Expected a ConnectionException");
167+ } catch (ConnectionException e) { /*expected*/}
198168 } finally {
199- completeRequests(requests);
169+ MockRequest.completeAll(allRequests);
200170 cluster.close();
201171 }
202172 }
@@ -211,7 +181,7 @@
211181 @Test(groups = "short")
212182 public void should_add_extra_connection_when_core_full() throws Exception {
213183 Cluster cluster = createClusterBuilder().build();
214- List<MockRequest> requests = newArrayList();
184+ List<MockRequest> allRequests = newArrayList();
215185 try {
216186 HostConnectionPool pool = createPool(cluster, 1, 2);
217187 Connection.Factory factory = spy(cluster.manager.connectionFactory);
@@ -219,13 +189,16 @@
219189 Connection core = pool.connections.get(0);
220190
221191 // Fill core connection + 1
222- requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
192+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
193+ assertBorrowedConnection(requests, core);
194+ allRequests.addAll(requests);
195+ allRequests.add(MockRequest.send(pool));
223196
224197 // Reaching the threshold should have triggered the creation of an extra one
225198 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
226199 assertPoolSize(pool, 2);
227200 } finally {
228- completeRequests(requests);
201+ MockRequest.completeAll(allRequests);
229202 cluster.close();
230203 }
231204 }
@@ -241,14 +214,17 @@
241214 @Test(groups = "long")
242215 public void should_resurrect_trashed_connection_within_idle_timeout() throws Exception {
243216 Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
244- List<MockRequest> requests = newArrayList();
217+ List<MockRequest> allRequests = newArrayList();
245218 try {
246219 HostConnectionPool pool = createPool(cluster, 1, 2);
247220 Connection.Factory factory = spy(cluster.manager.connectionFactory);
248221 cluster.manager.connectionFactory = factory;
249222 Connection connection1 = pool.connections.get(0);
250223
251- requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
224+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
225+ assertBorrowedConnections(requests, Collections.singletonList(connection1));
226+ allRequests.addAll(requests);
227+ allRequests.add(MockRequest.send(pool));
252228
253229 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
254230 assertPoolSize(pool, 2);
@@ -258,7 +234,7 @@
258234 assertThat(connection2.inFlight.get()).isEqualTo(0);
259235
260236 // Go back under the capacity of 1 connection
261- completeRequests(51, requests);
237+ MockRequest.completeMany(51, allRequests);
262238
263239 assertThat(connection1.inFlight.get()).isEqualTo(50);
264240 assertThat(connection2.inFlight.get()).isEqualTo(0);
@@ -269,7 +245,7 @@
269245 assertThat(pool.trash).containsExactly(connection1);
270246
271247 // Now borrow enough to go just under the 1 connection threshold
272- requests.addAll(sendRequests(50, pool));
248+ allRequests.addAll(MockRequest.sendMany(50, pool));
273249
274250 assertThat(pool.connections).containsExactly(connection2);
275251 assertThat(pool.trash).containsExactly(connection1);
@@ -277,7 +253,7 @@
277253 assertThat(connection2.inFlight.get()).isEqualTo(50);
278254
279255 // Borrowing one more time should resurrect the trashed connection
280- requests.addAll(sendRequests(1, pool));
256+ allRequests.addAll(MockRequest.sendMany(1, pool));
281257 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
282258 assertPoolSize(pool, 2);
283259
@@ -286,7 +262,7 @@
286262 assertThat(connection1.inFlight.get()).isEqualTo(50);
287263 assertThat(connection2.inFlight.get()).isEqualTo(51);
288264 } finally {
289- completeRequests(requests);
265+ MockRequest.completeAll(allRequests);
290266 cluster.close();
291267 }
292268 }
@@ -302,14 +278,17 @@
302278 @Test(groups = "long")
303279 public void should_not_resurrect_trashed_connection_after_idle_timeout() throws Exception {
304280 Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
305- List<MockRequest> requests = newArrayList();
281+ List<MockRequest> allRequests = newArrayList();
306282 try {
307283 HostConnectionPool pool = createPool(cluster, 1, 2);
308284 Connection.Factory factory = spy(cluster.manager.connectionFactory);
309285 cluster.manager.connectionFactory = factory;
310286 Connection connection1 = pool.connections.get(0);
311287
312- requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
288+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
289+ assertBorrowedConnection(requests, connection1);
290+ allRequests.addAll(requests);
291+ allRequests.add(MockRequest.send(pool));
313292
314293 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
315294 assertPoolSize(pool, 2);
@@ -320,7 +299,7 @@
320299 assertThat(connection2.inFlight.get()).isEqualTo(0);
321300
322301 // Go back under the capacity of 1 connection
323- completeRequests(51, requests);
302+ MockRequest.completeMany(51, allRequests);
324303
325304 assertThat(connection1.inFlight.get()).isEqualTo(50);
326305 assertThat(connection2.inFlight.get()).isEqualTo(0);
@@ -331,7 +310,7 @@
331310 assertThat(pool.trash).containsExactly(connection1);
332311
333312 // Return trashed connection down to 0 inFlight
334- completeRequests(50, requests);
313+ MockRequest.completeMany(50, allRequests);
335314 assertThat(connection1.inFlight.get()).isEqualTo(0);
336315
337316 // Give enough time for trashed connection to be cleaned up from the trash:
@@ -341,19 +320,22 @@
341320 assertThat(connection1.isClosed()).isTrue();
342321
343322 // Fill the live connection to go over the threshold where a second one is needed
344- requests.addAll(fillConnectionToThreshold(pool, singletonList(connection2)));
323+ requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
324+ assertBorrowedConnection(requests, connection2);
325+ allRequests.addAll(requests);
326+ allRequests.add(MockRequest.send(pool));
345327 assertThat(connection2.inFlight.get()).isEqualTo(101);
346328 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
347329 assertPoolSize(pool, 2);
348330
349331 // Borrow again to get the new connection
350332 MockRequest request = MockRequest.send(pool);
351- requests.add(request);
352- assertThat(request.connection)
333+ allRequests.add(request);
334+ assertThat(request.getConnection())
353335 .isNotEqualTo(connection2) // should not be the full connection
354336 .isNotEqualTo(connection1); // should not be the previously trashed one
355337 } finally {
356- completeRequests(requests);
338+ MockRequest.completeAll(allRequests);
357339 cluster.close();
358340 }
359341 }
@@ -368,7 +350,7 @@
368350 @Test(groups = "long")
369351 public void should_not_close_trashed_connection_until_no_in_flight() throws Exception {
370352 Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
371- List<MockRequest> requests = newArrayList();
353+ List<MockRequest> allRequests = newArrayList();
372354
373355 try {
374356 HostConnectionPool pool = createPool(cluster, 1, 2);
@@ -377,13 +359,16 @@
377359 Connection connection1 = pool.connections.get(0);
378360
379361 // Fill core connection enough to trigger creation of another one
380- requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
362+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
363+ assertBorrowedConnections(requests, Collections.singletonList(connection1));
364+ allRequests.addAll(requests);
365+ allRequests.add(MockRequest.send(pool));
381366
382367 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
383368 assertThat(pool.connections).hasSize(2);
384369
385370 // Return enough times to get back under the threshold where one connection is enough
386- completeRequests(50, requests);
371+ MockRequest.completeMany(50, allRequests);
387372
388373 // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
389374 // It still has in-flight requests so should not get closed.
@@ -393,7 +378,7 @@
393378 assertThat(connection1.isClosed()).isFalse();
394379
395380 // Consume all inFlight requests on the trashed connection.
396- completeRequests(51, requests);
381+ MockRequest.completeMany(51, allRequests);
397382
398383 // Sleep enough time for the connection to be consider idled and closed.
399384 Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS);
@@ -404,7 +389,7 @@
404389 assertThat(pool.connections).doesNotContain(connection1);
405390 assertThat(pool.trash).doesNotContain(connection1);
406391 } finally {
407- completeRequests(requests);
392+ MockRequest.completeAll(allRequests);
408393 cluster.close();
409394 }
410395 }
@@ -420,14 +405,17 @@
420405 @Test(groups = "short")
421406 public void should_trash_on_returning_connection_with_insufficient_streams() throws Exception {
422407 Cluster cluster = createClusterBuilder().build();
423- List<MockRequest> requests = newArrayList();
408+ List<MockRequest> allRequests = newArrayList();
424409 try {
425410 HostConnectionPool pool = createPool(cluster, 1, 2);
426411 Connection.Factory factory = spy(cluster.manager.connectionFactory);
427412 cluster.manager.connectionFactory = factory;
428413 Connection core = pool.connections.get(0);
429414
430- requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
415+ List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool);
416+ assertBorrowedConnections(requests, Collections.singletonList(core));
417+ allRequests.addAll(requests);
418+ allRequests.add(MockRequest.send(pool));
431419
432420 verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class));
433421 assertThat(pool.connections).hasSize(2);
@@ -437,7 +425,7 @@
437425 pool.connections.set(1, extra1);
438426
439427 // Borrow 10 times to ensure pool is utilized.
440- requests.addAll(sendRequests(10, pool));
428+ allRequests.addAll(MockRequest.sendMany(10, pool));
441429 assertThat(pool.connections).hasSize(2);
442430
443431 // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
@@ -449,7 +437,7 @@
449437 pool.returnConnection(extra1);
450438 assertThat(pool.trash).hasSize(1);
451439 } finally {
452- completeRequests(requests);
440+ MockRequest.completeAll(allRequests);
453441 cluster.close();
454442 }
455443 }
@@ -580,7 +568,7 @@
580568 .setConnectTimeoutMillis(readTimeout)
581569 .setReadTimeoutMillis(reconnectInterval))
582570 .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
583- List<MockRequest> requests = newArrayList();
571+ List<MockRequest> allRequests = newArrayList();
584572 try {
585573 cluster.init();
586574
@@ -608,8 +596,8 @@
608596
609597 // The borrowed connection should be the open one.
610598 MockRequest request = MockRequest.send(pool);
611- requests.add(request);
612- assertThat(request.connection).isEqualTo(core1);
599+ allRequests.add(request);
600+ assertThat(request.getConnection()).isEqualTo(core1);
613601
614602 // Should not have tried to create a new core connection since reconnection time had not elapsed.
615603 verify(factory, never()).open(any(HostConnectionPool.class));
@@ -620,8 +608,8 @@
620608 // Attempt to borrow connection, this should trigger ensureCoreConnections thus spawning a new connection.
621609 blockingExecutor.reset();
622610 request = MockRequest.send(pool);
623- requests.add(request);
624- assertThat(request.connection).isEqualTo(core1);
611+ allRequests.add(request);
612+ assertThat(request.getConnection()).isEqualTo(core1);
625613
626614 // Should have tried to open up to core connections as result of borrowing a connection past reconnect time and not being at core.
627615 blockingExecutor.blockUntilNextTaskCompleted();
@@ -638,23 +626,23 @@
638626
639627 // Try to borrow a connection, the pool should grow.
640628 blockingExecutor.reset();
641- requests.add(MockRequest.send(pool));
629+ allRequests.add(MockRequest.send(pool));
642630 blockingExecutor.blockUntilNextTaskCompleted();
643631 verify(factory).open(any(HostConnectionPool.class));
644632 reset(factory);
645633
646634 // Another core connection should be opened as result of another request to get us up to core connections.
647635 blockingExecutor.reset();
648- requests.add(MockRequest.send(pool));
636+ allRequests.add(MockRequest.send(pool));
649637 blockingExecutor.blockUntilNextTaskCompleted();
650638 verify(factory).open(any(HostConnectionPool.class));
651639 reset(factory);
652640
653641 // Sending another request should not grow the pool any more, since we are now at core connections.
654- requests.add(MockRequest.send(pool));
642+ allRequests.add(MockRequest.send(pool));
655643 verify(factory, after((reconnectInterval + readTimeout) * 2).never()).open(any(HostConnectionPool.class));
656644 } finally {
657- completeRequests(requests);
645+ MockRequest.completeAll(allRequests);
658646 cluster.close();
659647 }
660648 }
@@ -677,7 +665,7 @@
677665 .setConnectTimeoutMillis(readTimeout)
678666 .setReadTimeoutMillis(reconnectInterval))
679667 .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
680- List<MockRequest> requests = newArrayList();
668+ List<MockRequest> allRequests = newArrayList();
681669 try {
682670 cluster.init();
683671
@@ -691,7 +679,7 @@
691679 List<MockRequest> core0requests = newArrayList();
692680 for (int i = 0; i < 101; i++) {
693681 MockRequest request = MockRequest.send(pool);
694- assertThat(request.connection).isEqualTo(core0);
682+ assertThat(request.getConnection()).isEqualTo(core0);
695683 core0requests.add(request);
696684 }
697685
@@ -712,13 +700,15 @@
712700
713701 // Since core0 was closed, all of it's requests should have errored.
714702 for (MockRequest request : core0requests) {
715- verify(request, times(1)).onException(any(Connection.class), any(Exception.class), anyLong(), anyInt());
703+ assertThat(request.state.get()).isEqualTo(MockRequest.State.FAILED);
716704 }
717705
718706 assertThat(cluster).host(1).hasState(Host.State.UP);
719707
720708 // Create enough inFlight requests to fill connection.
721- requests.addAll(sendRequests(100, pool, singletonList(extra1)));
709+ List<MockRequest> requests = MockRequest.sendMany(100, pool);
710+ assertBorrowedConnections(requests, Collections.singletonList(extra1));
711+ allRequests.addAll(requests);
722712 assertThat(pool.connections).hasSize(1);
723713
724714 // A new connection should never have been spawned since we didn't max out core.
@@ -726,8 +716,8 @@
726716
727717 // Borrow another connection, since we exceed max another connection should be opened.
728718 MockRequest request = MockRequest.send(pool);
729- requests.add(request);
730- assertThat(request.connection).isEqualTo(extra1);
719+ allRequests.add(request);
720+ assertThat(request.getConnection()).isEqualTo(extra1);
731721
732722 // After some time the a connection should attempt to be opened (but will fail).
733723 verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
@@ -745,8 +735,8 @@
745735
746736 // Borrow another connection, since we exceed max another connection should be opened.
747737 request = MockRequest.send(pool);
748- requests.add(request);
749- assertThat(request.connection).isEqualTo(extra1);
738+ allRequests.add(request);
739+ assertThat(request.getConnection()).isEqualTo(extra1);
750740
751741 // Wait some reasonable amount of time for connection to reestablish then check pool size.
752742 Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
@@ -755,10 +745,10 @@
755745
756746 // Borrowed connection should be the newly spawned connection since the other one has some inflight requests.
757747 request = MockRequest.send(pool);
758- requests.add(request);
759- assertThat(request.connection).isNotEqualTo(core0).isNotEqualTo(extra1);
748+ allRequests.add(request);
749+ assertThat(request.getConnection()).isNotEqualTo(core0).isNotEqualTo(extra1);
760750 } finally {
761- completeRequests(requests);
751+ MockRequest.completeAll(allRequests);
762752 cluster.close();
763753 }
764754 }
@@ -781,7 +771,7 @@
781771 .setConnectTimeoutMillis(readTimeout)
782772 .setReadTimeoutMillis(reconnectInterval))
783773 .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
784- List<MockRequest> requests = newArrayList();
774+ List<MockRequest> allRequests = newArrayList();
785775 try {
786776 cluster.init();
787777
@@ -811,13 +801,13 @@
811801 // we need to wait for connections to be established between requests for the pool
812802 // to spawn new connections (since it only allows one simultaneous creation).
813803 for (int i = 5; i <= 8; i++) {
814- requests.add(MockRequest.send(pool));
804+ allRequests.add(MockRequest.send(pool));
815805 verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
816806 reset(factory);
817807 assertPoolSize(pool, i);
818808 }
819809 } finally {
820- completeRequests(requests);
810+ MockRequest.completeAll(allRequests);
821811 cluster.close();
822812 }
823813 }
@@ -825,15 +815,15 @@
825815 /**
826816 * Ensures that if all connections fail on pool init that the host and subsequently the
827817 * 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
818+ * The test also ensures that borrow attempts on the pool fail if we are still in the reconnection window
829819 * according to the ConvictionPolicy.
830820 *
831821 * @jira_ticket JAVA-544
832822 * @test_category connection:connection_pool
833823 * @since 2.0.11
834824 */
835- @Test(groups = "short", expectedExceptions = TimeoutException.class)
836- public void should_throw_exception_if_convicted_and_no_connections_available() throws Exception {
825+ @Test(groups = "short")
826+ public void should_throw_exception_if_convicted_and_no_connections_available() {
837827 int readTimeout = 1000;
838828 int reconnectInterval = 1000;
839829 Cluster cluster = this.createClusterBuilder()
@@ -862,7 +852,11 @@
862852 assertThat(cluster).host(1).hasState(Host.State.UP);
863853 assertThat(cluster).hasOpenControlConnection();
864854
865- MockRequest.send(pool);
855+ MockRequest failedBorrow = MockRequest.send(pool);
856+ try {
857+ failedBorrow.getConnection();
858+ fail("Expected a ConnectionException");
859+ } catch (ConnectionException e) { /*expected*/}
866860 } finally {
867861 cluster.close();
868862 }
@@ -871,7 +865,7 @@
871865
872866 /**
873867 * 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
868+ * control connection is not marked down. The test also ensures that when making requests
875869 * on the pool after the conviction period that all core connections are created.
876870 *
877871 * @jira_ticket JAVA-544
@@ -912,12 +906,13 @@
912906 Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
913907
914908 reset(factory);
915- MockRequest request = MockRequest.send(pool);
916- request.simulateSuccessResponse();
909+ MockRequest request = MockRequest.send(pool, 1);
917910
918911 // Should create up to core connections.
919912 verify(factory, timeout(readTimeout * 8).times(8)).open(any(HostConnectionPool.class));
920913 assertPoolSize(pool, 8);
914+
915+ request.simulateSuccessResponse();
921916 } finally {
922917 cluster.close();
923918 }
@@ -946,6 +941,9 @@
946941 cluster.init();
947942 assertThat(cluster).hasOpenControlConnection();
948943
944+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
945+ cluster.manager.connectionFactory = factory;
946+
949947 HostConnectionPool pool = createPool(cluster, 0, 2);
950948
951949 // Pool should be empty.
@@ -955,12 +953,14 @@
955953 assertThat(cluster).host(1).hasState(Host.State.UP);
956954 assertThat(cluster).hasOpenControlConnection();
957955
958- // Send a request, this should create a connection.
959- MockRequest request = MockRequest.send(pool);
960- request.simulateSuccessResponse();
956+ reset(factory);
957+ MockRequest request = MockRequest.send(pool, 1);
961958
962959 // Should create up to core connections.
960+ verify(factory, timeout(readTimeout).times(1)).open(any(HostConnectionPool.class));
963961 assertThat(pool.connections).hasSize(1);
962+
963+ request.simulateSuccessResponse();
964964 } finally {
965965 cluster.close();
966966 }
@@ -979,10 +979,10 @@
979979 }
980980
981981 /**
982- * <p>
982+ * <p/>
983983 * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the
984984 * insertions are being executed, the number of opened connection is monitored.
985- * <p>
985+ * <p/>
986986 * If at anytime, the number of opened connections is negative, this test will fail.
987987 *
988988 * @jira_ticket JAVA-349
@@ -1061,51 +1061,115 @@
10611061
10621062 enum State {START, COMPLETED, FAILED, TIMED_OUT}
10631063
1064- final Connection connection;
1065- private Connection.ResponseHandler responseHandler;
1064+ final ListenableFuture<Connection> connectionFuture;
1065+ private volatile Connection.ResponseHandler responseHandler;
1066+
1067+ final AtomicReference<State> state = new AtomicReference<State>(State.START);
1068+
1069+ static MockRequest send(HostConnectionPool pool) {
1070+ return send(pool, 0);
1071+ }
1072+
1073+ static MockRequest send(HostConnectionPool pool, int maxQueueSize) throws ConnectionException, BusyConnectionException {
1074+ return new MockRequest(pool, maxQueueSize);
1075+ }
1076+
1077+ private static List<MockRequest> sendMany(int count, HostConnectionPool pool) throws ConnectionException {
1078+ return sendMany(count, pool, 0);
1079+ }
1080+
1081+ private static List<MockRequest> sendMany(int count, HostConnectionPool pool, int maxQueueSize) throws ConnectionException {
1082+ List<MockRequest> requests = newArrayList();
1083+ for (int i = 0; i < count; i++) {
1084+ MockRequest request = send(pool, maxQueueSize);
1085+ requests.add(request);
1086+ }
1087+ return requests;
1088+ }
10661089
1067- private final AtomicReference<State> state = new AtomicReference<State>(State.START);
1090+ /**
1091+ * Completes count requests by simulating a successful response.
1092+ */
1093+ private static void completeMany(int count, List<MockRequest> requests) {
1094+ Iterator<MockRequest> requestIt = requests.iterator();
1095+ for (int i = 0; i < count; i++) {
1096+ if (requestIt.hasNext()) {
1097+ MockRequest request = requestIt.next();
1098+ request.simulateSuccessResponse();
1099+ requestIt.remove();
1100+ } else {
1101+ break;
1102+ }
1103+ }
1104+ }
10681105
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;
1106+ /**
1107+ * Completes all requests by simulating a successful response.
1108+ */
1109+ private static void completeAll(List<MockRequest> requests) {
1110+ for (MockRequest request : requests) {
1111+ request.simulateSuccessResponse();
1112+ }
10751113 }
10761114
1077- private MockRequest(HostConnectionPool pool) throws ConnectionException, TimeoutException, BusyConnectionException {
1078- connection = pool.borrowConnection(500, TimeUnit.MILLISECONDS);
1115+ private MockRequest(HostConnectionPool pool, int maxQueueSize) throws ConnectionException {
1116+ this.connectionFuture = pool.borrowConnection(maxQueueSize);
1117+ Futures.addCallback(this.connectionFuture, new MoreFutures.SuccessCallback<Connection>() {
1118+ @Override
1119+ public void onSuccess(Connection connection) {
1120+ MockRequest thisRequest = MockRequest.this;
1121+ thisRequest.responseHandler = new Connection.ResponseHandler(connection, -1, thisRequest);
1122+ connection.dispatcher.add(thisRequest.responseHandler);
1123+ }
1124+ });
10791125 }
10801126
10811127 void simulateSuccessResponse() {
1082- onSet(connection, null, 0, 0);
1128+ onSet(getConnection(), null, 0, 0);
10831129 }
10841130
10851131 @SuppressWarnings("unused")
10861132 void simulateErrorResponse() {
1087- onException(connection, null, 0, 0);
1133+ onException(getConnection(), null, 0, 0);
10881134 }
10891135
10901136 @SuppressWarnings("unused")
10911137 void simulateTimeout() {
1092- if (onTimeout(connection, 0, 0))
1138+ if (onTimeout(getConnection(), 0, 0))
10931139 responseHandler.cancelHandler();
10941140 }
10951141
1142+ // Get the connection, assuming pool acquisition completed
1143+ Connection getConnection() {
1144+ try {
1145+ if (!connectionFuture.isDone()) {
1146+ throw new AssertionError("Borrow call did not complete");
1147+ }
1148+ return Uninterruptibles.getUninterruptibly(connectionFuture);
1149+ } catch (ExecutionException e) {
1150+ throw Throwables.propagate(e.getCause());
1151+ }
1152+ }
1153+
10961154 @Override
10971155 public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
1156+ assertThat(connectionFuture.isDone()).isTrue();
1157+ try {
1158+ assertThat(Uninterruptibles.getUninterruptibly(connectionFuture)).isNotNull();
1159+ } catch (ExecutionException e) {
1160+ Throwables.propagate(e.getCause());
1161+ }
10981162 if (state.compareAndSet(State.START, State.COMPLETED)) {
1099- connection.release();
11001163 connection.dispatcher.removeHandler(responseHandler, true);
1164+ connection.release();
11011165 }
11021166 }
11031167
11041168 @Override
11051169 public void onException(Connection connection, Exception exception, long latency, int retryCount) {
11061170 if (state.compareAndSet(State.START, State.FAILED)) {
1107- connection.release();
11081171 connection.dispatcher.removeHandler(responseHandler, true);
1172+ connection.release();
11091173 }
11101174 }
11111175
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.