kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 0a5526490f498b75e8e3e2babf2aa8bf9b40cd8a612956f86a18154f301c12f7 |
|---|---|
| Author | Olivier Michallat <olim7t@users.noreply.github.com> · 2016-09-23 22:42 -07:00 |
| Committer | GitHub <noreply@github.com> · 2016-09-23 22:42 -07:00 |
| Parents | 0960065b032a, 307a50ac64a5 |
12 files changed
modified changelog/README.md +1 −0
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | - [improvement] JAVA-1293: Make DecoderForStreamIdSize.MAX_FRAME_LENGTH configurable. |
| 17 | 17 | - [improvement] JAVA-1053: Add a metric for authentication errors |
| 18 | 18 | - [improvement] JAVA-1263: Eliminate unnecessary memory copies in FrameCompressor implementations. |
| 19 | +- [improvement] JAVA-893: Make connection pool non-blocking | |
| 19 | 20 | |
| 20 | 21 | |
| 21 | 22 | ### 3.0.3 |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +92 −23
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | import com.datastax.driver.core.exceptions.*; |
| 20 | 20 | import com.datastax.driver.core.utils.MoreFutures; |
| 21 | 21 | import com.google.common.annotations.VisibleForTesting; |
| 22 | +import com.google.common.base.Objects; | |
| 22 | 23 | import com.google.common.collect.Lists; |
| 23 | 24 | import com.google.common.collect.MapMaker; |
| 24 | 25 | import com.google.common.util.concurrent.*; |
| @@ -85,7 +86,9 @@ | ||
| 85 | 86 | final AtomicInteger inFlight = new AtomicInteger(0); |
| 86 | 87 | |
| 87 | 88 | private final AtomicInteger writer = new AtomicInteger(0); |
| 88 | - private volatile String keyspace; | |
| 89 | + | |
| 90 | + private final AtomicReference<SetKeyspaceAttempt> targetKeyspace; | |
| 91 | + private final SetKeyspaceAttempt defaultKeyspaceAttempt; | |
| 89 | 92 | |
| 90 | 93 | private volatile boolean isInitialized; |
| 91 | 94 | private final AtomicBoolean isDefunct = new AtomicBoolean(); |
| @@ -95,8 +98,9 @@ | ||
| 95 | 98 | |
| 96 | 99 | private final AtomicReference<Owner> ownerRef = new AtomicReference<Owner>(); |
| 97 | 100 | |
| 101 | + private final ListenableFuture<Connection> thisFuture; | |
| 102 | + | |
| 98 | 103 | /** |
| 99 | - * /** | |
| 100 | 104 | * Create a new connection to a Cassandra node and associate it with the given pool. |
| 101 | 105 | * |
| 102 | 106 | * @param name the connection name |
| @@ -111,6 +115,9 @@ | ||
| 111 | 115 | this.dispatcher = new Dispatcher(); |
| 112 | 116 | this.name = name; |
| 113 | 117 | this.ownerRef.set(owner); |
| 118 | + this.thisFuture = Futures.immediateFuture(this); | |
| 119 | + this.defaultKeyspaceAttempt = new SetKeyspaceAttempt(null, thisFuture); | |
| 120 | + this.targetKeyspace = new AtomicReference<SetKeyspaceAttempt>(defaultKeyspaceAttempt); | |
| 114 | 121 | } |
| 115 | 122 | |
| 116 | 123 | /** |
| @@ -418,7 +425,6 @@ | ||
| 418 | 425 | else if (Host.statesLogger.isDebugEnabled()) |
| 419 | 426 | Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage()); |
| 420 | 427 | |
| 421 | - | |
| 422 | 428 | Host host = factory.manager.metadata.getHost(address); |
| 423 | 429 | if (host != null) { |
| 424 | 430 | // Sometimes close() can be called before defunct(); avoid decrementing the connection count twice, but |
| @@ -452,14 +458,14 @@ | ||
| 452 | 458 | } |
| 453 | 459 | |
| 454 | 460 | String keyspace() { |
| 455 | - return keyspace; | |
| 461 | + return targetKeyspace.get().keyspace; | |
| 456 | 462 | } |
| 457 | 463 | |
| 458 | 464 | void setKeyspace(String keyspace) throws ConnectionException { |
| 459 | 465 | if (keyspace == null) |
| 460 | 466 | return; |
| 461 | 467 | |
| 462 | - if (this.keyspace != null && this.keyspace.equals(keyspace)) | |
| 468 | + if (Objects.equal(keyspace(), keyspace)) | |
| 463 | 469 | return; |
| 464 | 470 | |
| 465 | 471 | try { |
| @@ -483,24 +489,59 @@ | ||
| 483 | 489 | } |
| 484 | 490 | } |
| 485 | 491 | |
| 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; | |
| 502 | 543 | } |
| 503 | - }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor()); | |
| 544 | + } | |
| 504 | 545 | } |
| 505 | 546 | |
| 506 | 547 | /** |
| @@ -1181,6 +1222,34 @@ | ||
| 1181 | 1222 | } |
| 1182 | 1223 | } |
| 1183 | 1224 | |
| 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 | + | |
| 1184 | 1253 | static class Future extends AbstractFuture<Message.Response> implements RequestHandler.Callback { |
| 1185 | 1254 | |
| 1186 | 1255 | private final Message.Request request; |
| @@ -1350,7 +1419,7 @@ | ||
| 1350 | 1419 | pipeline.addLast("ssl", sslOptions.newSSLHandler(channel)); |
| 1351 | 1420 | } |
| 1352 | 1421 | |
| 1353 | -// pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO)); | |
| 1422 | + // pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO)); | |
| 1354 | 1423 | |
| 1355 | 1424 | pipeline.addLast("frameDecoder", new Frame.Decoder()); |
| 1356 | 1425 | pipeline.addLast("frameEncoder", frameEncoder); |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +95 −113
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 19 | +import com.datastax.driver.core.exceptions.BusyPoolException; | |
| 19 | 20 | import com.datastax.driver.core.exceptions.ConnectionException; |
| 20 | 21 | import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException; |
| 21 | 22 | import com.datastax.driver.core.utils.MoreFutures; |
| @@ -26,16 +27,10 @@ | ||
| 26 | 27 | import org.slf4j.Logger; |
| 27 | 28 | import org.slf4j.LoggerFactory; |
| 28 | 29 | |
| 29 | -import java.util.ArrayList; | |
| 30 | -import java.util.List; | |
| 31 | -import java.util.ListIterator; | |
| 32 | -import java.util.Set; | |
| 30 | +import java.util.*; | |
| 33 | 31 | import java.util.concurrent.*; |
| 34 | 32 | import java.util.concurrent.atomic.AtomicInteger; |
| 35 | 33 | 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; | |
| 39 | 34 | |
| 40 | 35 | import static com.datastax.driver.core.Connection.State.*; |
| 41 | 36 | |
| @@ -62,9 +57,8 @@ | ||
| 62 | 57 | @VisibleForTesting |
| 63 | 58 | final Set<Connection> trash = new CopyOnWriteArraySet<Connection>(); |
| 64 | 59 | |
| 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(); | |
| 68 | 62 | |
| 69 | 63 | private final Runnable newConnectionTask; |
| 70 | 64 | |
| @@ -81,7 +75,7 @@ | ||
| 81 | 75 | // following threshold, we just replace the connection by a new one. |
| 82 | 76 | private final int minAllowedStreams; |
| 83 | 77 | |
| 84 | - public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) { | |
| 78 | + HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) { | |
| 85 | 79 | assert hostDistance != HostDistance.IGNORED; |
| 86 | 80 | this.host = host; |
| 87 | 81 | this.hostDistance = hostDistance; |
| @@ -196,17 +190,13 @@ | ||
| 196 | 190 | return manager.configuration().getPoolingOptions(); |
| 197 | 191 | } |
| 198 | 192 | |
| 199 | - public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { | |
| 193 | + ListenableFuture<Connection> borrowConnection(int maxQueueSize) { | |
| 200 | 194 | Phase phase = this.phase.get(); |
| 201 | 195 | 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)); | |
| 205 | 197 | |
| 206 | 198 | 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()) { | |
| 210 | 200 | int coreSize = options().getCoreConnectionsPerHost(hostDistance); |
| 211 | 201 | if (coreSize == 0) { |
| 212 | 202 | maybeSpawnNewConnection(); |
| @@ -218,10 +208,7 @@ | ||
| 218 | 208 | manager.blockingExecutor().submit(newConnectionTask); |
| 219 | 209 | } |
| 220 | 210 | } |
| 221 | - Connection c = waitForConnection(timeout, unit); | |
| 222 | - totalInFlight.incrementAndGet(); | |
| 223 | - c.setKeyspace(manager.poolsState.keyspace); | |
| 224 | - return c; | |
| 211 | + return enqueue(maxQueueSize); | |
| 225 | 212 | } |
| 226 | 213 | } |
| 227 | 214 | |
| @@ -238,18 +225,17 @@ | ||
| 238 | 225 | if (leastBusy == null) { |
| 239 | 226 | // We could have raced with a shutdown since the last check |
| 240 | 227 | if (isClosed()) |
| 241 | - throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown"); | |
| 228 | + return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is shutdown")); | |
| 242 | 229 | // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between |
| 243 | 230 | // the previous check to connections and now. But in that case, the line above will have trigger the creation of |
| 244 | 231 | // a new connection, so just wait that connection and move on |
| 245 | - leastBusy = waitForConnection(timeout, unit); | |
| 232 | + return enqueue(maxQueueSize); | |
| 246 | 233 | } else { |
| 247 | 234 | while (true) { |
| 248 | 235 | int inFlight = leastBusy.inFlight.get(); |
| 249 | 236 | |
| 250 | 237 | if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) { |
| 251 | - leastBusy = waitForConnection(timeout, unit); | |
| 252 | - break; | |
| 238 | + return enqueue(maxQueueSize); | |
| 253 | 239 | } |
| 254 | 240 | |
| 255 | 241 | if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1)) |
| @@ -276,96 +262,37 @@ | ||
| 276 | 262 | maybeSpawnNewConnection(); |
| 277 | 263 | } |
| 278 | 264 | |
| 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); | |
| 305 | 266 | } |
| 306 | 267 | |
| 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)); | |
| 317 | 271 | } |
| 318 | - } | |
| 319 | 272 | |
| 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)); | |
| 333 | 277 | } |
| 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; | |
| 346 | 280 | } |
| 281 | + } | |
| 347 | 282 | |
| 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); | |
| 361 | 285 | |
| 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 | + } | |
| 364 | 291 | |
| 365 | - throw new TimeoutException("All connections are busy"); | |
| 292 | + return future; | |
| 366 | 293 | } |
| 367 | 294 | |
| 368 | - public void returnConnection(Connection connection) { | |
| 295 | + void returnConnection(Connection connection) { | |
| 369 | 296 | connection.inFlight.decrementAndGet(); |
| 370 | 297 | totalInFlight.decrementAndGet(); |
| 371 | 298 | |
| @@ -384,7 +311,60 @@ | ||
| 384 | 311 | if (connection.maxAvailableStreams() < minAllowedStreams) { |
| 385 | 312 | replaceConnection(connection); |
| 386 | 313 | } 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 | + } | |
| 388 | 368 | } |
| 389 | 369 | } |
| 390 | 370 | } |
| @@ -453,6 +433,7 @@ | ||
| 453 | 433 | } |
| 454 | 434 | logger.debug("Creating new connection on busy pool to {}", host); |
| 455 | 435 | newConnection = manager.connectionFactory().open(this); |
| 436 | + newConnection.setKeyspace(manager.poolsState.keyspace); | |
| 456 | 437 | } |
| 457 | 438 | connections.add(newConnection); |
| 458 | 439 | |
| @@ -465,7 +446,7 @@ | ||
| 465 | 446 | return false; |
| 466 | 447 | } |
| 467 | 448 | |
| 468 | - signalAvailableConnection(); | |
| 449 | + dequeue(newConnection); | |
| 469 | 450 | return true; |
| 470 | 451 | } catch (InterruptedException e) { |
| 471 | 452 | Thread.currentThread().interrupt(); |
| @@ -600,11 +581,11 @@ | ||
| 600 | 581 | connection.closeAsync(); |
| 601 | 582 | } |
| 602 | 583 | |
| 603 | - public final boolean isClosed() { | |
| 584 | + final boolean isClosed() { | |
| 604 | 585 | return closeFuture.get() != null; |
| 605 | 586 | } |
| 606 | 587 | |
| 607 | - public final CloseFuture closeAsync() { | |
| 588 | + final CloseFuture closeAsync() { | |
| 608 | 589 | |
| 609 | 590 | CloseFuture future = closeFuture.get(); |
| 610 | 591 | if (future != null) |
| @@ -612,8 +593,9 @@ | ||
| 612 | 593 | |
| 613 | 594 | phase.set(Phase.CLOSING); |
| 614 | 595 | |
| 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 | + } | |
| 617 | 599 | |
| 618 | 600 | future = new CloseFuture.Forwarding(discardAvailableConnections()); |
| 619 | 601 | |
| @@ -622,7 +604,7 @@ | ||
| 622 | 604 | : closeFuture.get(); // We raced, it's ok, return the future that was actually set |
| 623 | 605 | } |
| 624 | 606 | |
| 625 | - public int opened() { | |
| 607 | + int opened() { | |
| 626 | 608 | return open.get(); |
| 627 | 609 | } |
| 628 | 610 | |
| @@ -657,7 +639,7 @@ | ||
| 657 | 639 | |
| 658 | 640 | // This creates connections if we have less than core connections (if we |
| 659 | 641 | // have more than core, connection will just get trash when we can). |
| 660 | - public void ensureCoreConnections() { | |
| 642 | + void ensureCoreConnections() { | |
| 661 | 643 | if (isClosed()) |
| 662 | 644 | return; |
| 663 | 645 |
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +40 −16
| @@ -128,10 +128,16 @@ | ||
| 128 | 128 | public static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120; |
| 129 | 129 | |
| 130 | 130 | /** |
| 131 | - * The default value for {@link #getPoolTimeoutMillis()} ({@value}). | |
| 131 | + * @deprecated see {@link #setPoolTimeoutMillis(int)} | |
| 132 | 132 | */ |
| 133 | + @Deprecated | |
| 133 | 134 | public static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000; |
| 134 | 135 | |
| 136 | + /** | |
| 137 | + * The default value for {@link #getMaxQueueSize()} ({@value}). | |
| 138 | + */ | |
| 139 | + public static final int DEFAULT_MAX_QUEUE_SIZE = 256; | |
| 140 | + | |
| 135 | 141 | /** |
| 136 | 142 | * The default value for {@link #getHeartbeatIntervalSeconds()} ({@value}). |
| 137 | 143 | */ |
| @@ -151,7 +157,7 @@ | ||
| 151 | 157 | private volatile int maxRequestsPerConnectionRemote = UNSET; |
| 152 | 158 | |
| 153 | 159 | 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; | |
| 155 | 161 | private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS; |
| 156 | 162 | |
| 157 | 163 | private volatile Executor initializationExecutor = DEFAULT_INITIALIZATION_EXECUTOR; |
| @@ -400,30 +406,48 @@ | ||
| 400 | 406 | } |
| 401 | 407 | |
| 402 | 408 | /** |
| 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. | |
| 406 | 410 | */ |
| 411 | + @Deprecated | |
| 407 | 412 | 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; | |
| 409 | 432 | } |
| 410 | 433 | |
| 411 | 434 | /** |
| 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. | |
| 413 | 436 | * <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. | |
| 416 | 439 | * <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. | |
| 418 | 442 | * |
| 419 | - * @param poolTimeoutMillis the new value in milliseconds. | |
| 443 | + * @param maxQueueSize the new value. | |
| 420 | 444 | * @return this {@code PoolingOptions} |
| 421 | - * @throws IllegalArgumentException if the timeout is negative. | |
| 445 | + * @throws IllegalArgumentException if the value is negative. | |
| 422 | 446 | */ |
| 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; | |
| 427 | 451 | return this; |
| 428 | 452 | } |
| 429 | 453 |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +61 −57
| @@ -21,6 +21,9 @@ | ||
| 21 | 21 | import com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type; |
| 22 | 22 | import com.datastax.driver.core.policies.SpeculativeExecutionPolicy.SpeculativeExecutionPlan; |
| 23 | 23 | 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; | |
| 24 | 27 | import io.netty.util.Timeout; |
| 25 | 28 | import io.netty.util.TimerTask; |
| 26 | 29 | import org.slf4j.Logger; |
| @@ -108,7 +111,7 @@ | ||
| 108 | 111 | |
| 109 | 112 | SpeculativeExecution execution = new SpeculativeExecution(request, position); |
| 110 | 113 | runningExecutions.add(execution); |
| 111 | - execution.sendRequest(); | |
| 114 | + execution.findNextHostAndQuery(); | |
| 112 | 115 | } |
| 113 | 116 | |
| 114 | 117 | private void scheduleExecution(long delayMillis) { |
| @@ -261,12 +264,10 @@ | ||
| 261 | 264 | logger.trace("[{}] Starting", id); |
| 262 | 265 | } |
| 263 | 266 | |
| 264 | - void sendRequest() { | |
| 267 | + void findNextHostAndQuery() { | |
| 265 | 268 | try { |
| 266 | 269 | Host host; |
| 267 | 270 | while (!isDone.get() && (host = queryPlan.next()) != null && !queryStateRef.get().isCancelled()) { |
| 268 | - if (logger.isTraceEnabled()) | |
| 269 | - logger.trace("[{}] Querying node {}", id, host); | |
| 270 | 271 | if (query(host)) |
| 271 | 272 | return; |
| 272 | 273 | } |
| @@ -278,48 +279,63 @@ | ||
| 278 | 279 | } |
| 279 | 280 | |
| 280 | 281 | 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()) | |
| 283 | 284 | return false; |
| 284 | 285 | |
| 286 | + if (logger.isTraceEnabled()) | |
| 287 | + logger.trace("[{}] Querying node {}", id, host); | |
| 288 | + | |
| 285 | 289 | if (allowSpeculativeExecutions && nextExecutionScheduled.compareAndSet(false, true)) |
| 286 | 290 | scheduleExecution(speculativeExecutionPlan.nextExecution(host)); |
| 287 | 291 | |
| 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 | + } | |
| 295 | 325 | } |
| 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; | |
| 323 | 339 | } |
| 324 | 340 | |
| 325 | 341 | private void write(Connection connection, Connection.ResponseCallback responseCallback) throws ConnectionException, BusyConnectionException { |
| @@ -382,23 +398,11 @@ | ||
| 382 | 398 | if (newConsistencyLevel != null) |
| 383 | 399 | this.retryConsistencyLevel = newConsistencyLevel; |
| 384 | 400 | |
| 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(); | |
| 402 | 406 | } |
| 403 | 407 | |
| 404 | 408 | 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 @@ | ||
| 623 | 623 | |
| 624 | 624 | try { |
| 625 | 625 | // 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 | + } | |
| 634 | 638 | |
| 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); | |
| 642 | 650 | } catch (Exception e) { |
| 643 | 651 | // Again, not being able to prepare the query right now is no big deal, so just ignore |
| 644 | 652 | } |
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 @@ | ||
| 110 | 110 | } |
| 111 | 111 | }); |
| 112 | 112 | |
| 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; | |
| 116 | 114 | try { |
| 117 | 115 | ResultSet result = future.get(waitTimeInMs, TimeUnit.MILLISECONDS); |
| 118 | 116 | 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 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | 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.*; | |
| 21 | 20 | import com.datastax.driver.core.policies.ConstantReconnectionPolicy; |
| 21 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 22 | 22 | import com.google.common.base.Predicate; |
| 23 | +import com.google.common.base.Throwables; | |
| 23 | 24 | import com.google.common.util.concurrent.*; |
| 24 | 25 | import org.scassandra.cql.PrimitiveType; |
| 25 | 26 | import org.scassandra.http.client.PrimingRequest; |
| @@ -27,6 +28,7 @@ | ||
| 27 | 28 | import org.testng.annotations.Test; |
| 28 | 29 | |
| 29 | 30 | import java.net.InetSocketAddress; |
| 31 | +import java.util.Collections; | |
| 30 | 32 | import java.util.Iterator; |
| 31 | 33 | import java.util.List; |
| 32 | 34 | import java.util.concurrent.*; |
| @@ -35,8 +37,8 @@ | ||
| 35 | 37 | |
| 36 | 38 | import static com.datastax.driver.core.Assertions.assertThat; |
| 37 | 39 | import static com.datastax.driver.core.ConditionChecker.check; |
| 40 | +import static com.datastax.driver.core.PoolingOptions.NEW_CONNECTION_THRESHOLD_LOCAL_KEY; | |
| 38 | 41 | import static com.google.common.collect.Lists.newArrayList; |
| 39 | -import static java.util.Collections.singletonList; | |
| 40 | 42 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 41 | 43 | import static org.mockito.Mockito.*; |
| 42 | 44 | import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE; |
| @@ -45,6 +47,9 @@ | ||
| 45 | 47 | |
| 46 | 48 | public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster { |
| 47 | 49 | |
| 50 | + static final Integer NEW_CONNECTION_THRESHOLD = PoolingOptions.DEFAULTS.get(ProtocolVersion.V1) | |
| 51 | + .get(NEW_CONNECTION_THRESHOLD_LOCAL_KEY); | |
| 52 | + | |
| 48 | 53 | @BeforeClass(groups = {"short", "long"}) |
| 49 | 54 | public void reinitializeCluster() { |
| 50 | 55 | // Don't use the provided cluster, each test will create its own instead. |
| @@ -67,136 +72,317 @@ | ||
| 67 | 72 | }).becomesTrue(); |
| 68 | 73 | } |
| 69 | 74 | |
| 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)); | |
| 77 | 83 | } |
| 78 | 84 | |
| 79 | 85 | /** |
| 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 | |
| 81 | 92 | */ |
| 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 | + } | |
| 84 | 120 | } |
| 85 | 121 | |
| 86 | 122 | /** |
| 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 | |
| 88 | 128 | */ |
| 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(); | |
| 90 | 132 | 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 | + } | |
| 98 | 161 | } |
| 99 | 162 | |
| 100 | 163 | /** |
| 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 | |
| 102 | 172 | */ |
| 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 | + } | |
| 112 | 232 | } |
| 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(); | |
| 113 | 240 | } |
| 114 | 241 | } |
| 115 | 242 | |
| 116 | 243 | /** |
| 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 | |
| 118 | 250 | */ |
| 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(); | |
| 122 | 278 | } |
| 123 | 279 | } |
| 124 | 280 | |
| 125 | 281 | /** |
| 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. | |
| 128 | 284 | * |
| 129 | - * @jira_ticket JAVA-419 | |
| 285 | + * @jira_ticket JAVA-839 | |
| 130 | 286 | * @test_category connection:connection_pool |
| 131 | - * @since 2.0.10, 2.1.6 | |
| 287 | + * @since 3.0.4, 3.1.1 | |
| 132 | 288 | */ |
| 133 | 289 | @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 { | |
| 135 | 291 | Cluster cluster = createClusterBuilder().build(); |
| 136 | 292 | List<MockRequest> requests = newArrayList(); |
| 137 | 293 | 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; | |
| 139 | 298 | |
| 140 | - assertThat(pool.connections.size()).isEqualTo(2); | |
| 299 | + assertThat(pool.connections.size()).isEqualTo(1); | |
| 141 | 300 | 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); | |
| 143 | 324 | |
| 144 | 325 | 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 | + | |
| 148 | 333 | } finally { |
| 149 | - completeRequests(requests); | |
| 334 | + MockRequest.completeAll(requests); | |
| 150 | 335 | cluster.close(); |
| 151 | 336 | } |
| 152 | 337 | } |
| 153 | 338 | |
| 154 | 339 | /** |
| 155 | 340 | * 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. | |
| 157 | 342 | * |
| 158 | 343 | * @jira_ticket JAVA-419 |
| 159 | 344 | * @test_category connection:connection_pool |
| 160 | 345 | * @since 2.0.10, 2.1.6 |
| 161 | 346 | */ |
| 162 | 347 | @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 { | |
| 164 | 349 | Cluster cluster = createClusterBuilder().build(); |
| 165 | - List<MockRequest> requests = newArrayList(); | |
| 350 | + List<MockRequest> allRequests = newArrayList(); | |
| 166 | 351 | try { |
| 167 | 352 | HostConnectionPool pool = createPool(cluster, 1, 2); |
| 168 | 353 | Connection.Factory factory = spy(cluster.manager.connectionFactory); |
| 169 | 354 | cluster.manager.connectionFactory = factory; |
| 170 | 355 | |
| 171 | 356 | assertThat(pool.connections.size()).isEqualTo(1); |
| 172 | - List<Connection> coreConnections = newArrayList(pool.connections); | |
| 357 | + Connection coreConnection = pool.connections.get(0); | |
| 173 | 358 | |
| 174 | 359 | // 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)); | |
| 176 | 364 | |
| 177 | 365 | // Allow time for new connection to be spawned. |
| 178 | 366 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 179 | 367 | assertPoolSize(pool, 2); |
| 180 | 368 | |
| 181 | 369 | // 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++) { | |
| 183 | 371 | 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); | |
| 186 | 374 | } |
| 187 | 375 | |
| 188 | 376 | // Fill remaining connections (28 + 28) - 1 |
| 189 | - requests.addAll(sendRequests(55, pool)); | |
| 377 | + allRequests.addAll(MockRequest.sendMany(55, pool)); | |
| 190 | 378 | |
| 191 | - boolean timedOut = false; | |
| 379 | + MockRequest failedBorrow = MockRequest.send(pool); | |
| 192 | 380 | 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*/} | |
| 198 | 384 | } finally { |
| 199 | - completeRequests(requests); | |
| 385 | + MockRequest.completeAll(allRequests); | |
| 200 | 386 | cluster.close(); |
| 201 | 387 | } |
| 202 | 388 | } |
| @@ -211,7 +397,7 @@ | ||
| 211 | 397 | @Test(groups = "short") |
| 212 | 398 | public void should_add_extra_connection_when_core_full() throws Exception { |
| 213 | 399 | Cluster cluster = createClusterBuilder().build(); |
| 214 | - List<MockRequest> requests = newArrayList(); | |
| 400 | + List<MockRequest> allRequests = newArrayList(); | |
| 215 | 401 | try { |
| 216 | 402 | HostConnectionPool pool = createPool(cluster, 1, 2); |
| 217 | 403 | Connection.Factory factory = spy(cluster.manager.connectionFactory); |
| @@ -219,13 +405,16 @@ | ||
| 219 | 405 | Connection core = pool.connections.get(0); |
| 220 | 406 | |
| 221 | 407 | // 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)); | |
| 223 | 412 | |
| 224 | 413 | // Reaching the threshold should have triggered the creation of an extra one |
| 225 | 414 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 226 | 415 | assertPoolSize(pool, 2); |
| 227 | 416 | } finally { |
| 228 | - completeRequests(requests); | |
| 417 | + MockRequest.completeAll(allRequests); | |
| 229 | 418 | cluster.close(); |
| 230 | 419 | } |
| 231 | 420 | } |
| @@ -241,14 +430,17 @@ | ||
| 241 | 430 | @Test(groups = "long") |
| 242 | 431 | public void should_resurrect_trashed_connection_within_idle_timeout() throws Exception { |
| 243 | 432 | Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build(); |
| 244 | - List<MockRequest> requests = newArrayList(); | |
| 433 | + List<MockRequest> allRequests = newArrayList(); | |
| 245 | 434 | try { |
| 246 | 435 | HostConnectionPool pool = createPool(cluster, 1, 2); |
| 247 | 436 | Connection.Factory factory = spy(cluster.manager.connectionFactory); |
| 248 | 437 | cluster.manager.connectionFactory = factory; |
| 249 | 438 | Connection connection1 = pool.connections.get(0); |
| 250 | 439 | |
| 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)); | |
| 252 | 444 | |
| 253 | 445 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 254 | 446 | assertPoolSize(pool, 2); |
| @@ -258,7 +450,7 @@ | ||
| 258 | 450 | assertThat(connection2.inFlight.get()).isEqualTo(0); |
| 259 | 451 | |
| 260 | 452 | // Go back under the capacity of 1 connection |
| 261 | - completeRequests(51, requests); | |
| 453 | + MockRequest.completeMany(51, allRequests); | |
| 262 | 454 | |
| 263 | 455 | assertThat(connection1.inFlight.get()).isEqualTo(50); |
| 264 | 456 | assertThat(connection2.inFlight.get()).isEqualTo(0); |
| @@ -269,7 +461,7 @@ | ||
| 269 | 461 | assertThat(pool.trash).containsExactly(connection1); |
| 270 | 462 | |
| 271 | 463 | // Now borrow enough to go just under the 1 connection threshold |
| 272 | - requests.addAll(sendRequests(50, pool)); | |
| 464 | + allRequests.addAll(MockRequest.sendMany(50, pool)); | |
| 273 | 465 | |
| 274 | 466 | assertThat(pool.connections).containsExactly(connection2); |
| 275 | 467 | assertThat(pool.trash).containsExactly(connection1); |
| @@ -277,7 +469,7 @@ | ||
| 277 | 469 | assertThat(connection2.inFlight.get()).isEqualTo(50); |
| 278 | 470 | |
| 279 | 471 | // Borrowing one more time should resurrect the trashed connection |
| 280 | - requests.addAll(sendRequests(1, pool)); | |
| 472 | + allRequests.addAll(MockRequest.sendMany(1, pool)); | |
| 281 | 473 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 282 | 474 | assertPoolSize(pool, 2); |
| 283 | 475 | |
| @@ -286,7 +478,7 @@ | ||
| 286 | 478 | assertThat(connection1.inFlight.get()).isEqualTo(50); |
| 287 | 479 | assertThat(connection2.inFlight.get()).isEqualTo(51); |
| 288 | 480 | } finally { |
| 289 | - completeRequests(requests); | |
| 481 | + MockRequest.completeAll(allRequests); | |
| 290 | 482 | cluster.close(); |
| 291 | 483 | } |
| 292 | 484 | } |
| @@ -302,14 +494,17 @@ | ||
| 302 | 494 | @Test(groups = "long") |
| 303 | 495 | public void should_not_resurrect_trashed_connection_after_idle_timeout() throws Exception { |
| 304 | 496 | Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build(); |
| 305 | - List<MockRequest> requests = newArrayList(); | |
| 497 | + List<MockRequest> allRequests = newArrayList(); | |
| 306 | 498 | try { |
| 307 | 499 | HostConnectionPool pool = createPool(cluster, 1, 2); |
| 308 | 500 | Connection.Factory factory = spy(cluster.manager.connectionFactory); |
| 309 | 501 | cluster.manager.connectionFactory = factory; |
| 310 | 502 | Connection connection1 = pool.connections.get(0); |
| 311 | 503 | |
| 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)); | |
| 313 | 508 | |
| 314 | 509 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 315 | 510 | assertPoolSize(pool, 2); |
| @@ -320,7 +515,7 @@ | ||
| 320 | 515 | assertThat(connection2.inFlight.get()).isEqualTo(0); |
| 321 | 516 | |
| 322 | 517 | // Go back under the capacity of 1 connection |
| 323 | - completeRequests(51, requests); | |
| 518 | + MockRequest.completeMany(51, allRequests); | |
| 324 | 519 | |
| 325 | 520 | assertThat(connection1.inFlight.get()).isEqualTo(50); |
| 326 | 521 | assertThat(connection2.inFlight.get()).isEqualTo(0); |
| @@ -331,7 +526,7 @@ | ||
| 331 | 526 | assertThat(pool.trash).containsExactly(connection1); |
| 332 | 527 | |
| 333 | 528 | // Return trashed connection down to 0 inFlight |
| 334 | - completeRequests(50, requests); | |
| 529 | + MockRequest.completeMany(50, allRequests); | |
| 335 | 530 | assertThat(connection1.inFlight.get()).isEqualTo(0); |
| 336 | 531 | |
| 337 | 532 | // Give enough time for trashed connection to be cleaned up from the trash: |
| @@ -341,19 +536,22 @@ | ||
| 341 | 536 | assertThat(connection1.isClosed()).isTrue(); |
| 342 | 537 | |
| 343 | 538 | // 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)); | |
| 345 | 543 | assertThat(connection2.inFlight.get()).isEqualTo(101); |
| 346 | 544 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 347 | 545 | assertPoolSize(pool, 2); |
| 348 | 546 | |
| 349 | 547 | // Borrow again to get the new connection |
| 350 | 548 | MockRequest request = MockRequest.send(pool); |
| 351 | - requests.add(request); | |
| 352 | - assertThat(request.connection) | |
| 549 | + allRequests.add(request); | |
| 550 | + assertThat(request.getConnection()) | |
| 353 | 551 | .isNotEqualTo(connection2) // should not be the full connection |
| 354 | 552 | .isNotEqualTo(connection1); // should not be the previously trashed one |
| 355 | 553 | } finally { |
| 356 | - completeRequests(requests); | |
| 554 | + MockRequest.completeAll(allRequests); | |
| 357 | 555 | cluster.close(); |
| 358 | 556 | } |
| 359 | 557 | } |
| @@ -368,7 +566,7 @@ | ||
| 368 | 566 | @Test(groups = "long") |
| 369 | 567 | public void should_not_close_trashed_connection_until_no_in_flight() throws Exception { |
| 370 | 568 | Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build(); |
| 371 | - List<MockRequest> requests = newArrayList(); | |
| 569 | + List<MockRequest> allRequests = newArrayList(); | |
| 372 | 570 | |
| 373 | 571 | try { |
| 374 | 572 | HostConnectionPool pool = createPool(cluster, 1, 2); |
| @@ -377,13 +575,16 @@ | ||
| 377 | 575 | Connection connection1 = pool.connections.get(0); |
| 378 | 576 | |
| 379 | 577 | // 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)); | |
| 381 | 582 | |
| 382 | 583 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 383 | 584 | assertThat(pool.connections).hasSize(2); |
| 384 | 585 | |
| 385 | 586 | // Return enough times to get back under the threshold where one connection is enough |
| 386 | - completeRequests(50, requests); | |
| 587 | + MockRequest.completeMany(50, allRequests); | |
| 387 | 588 | |
| 388 | 589 | // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one. |
| 389 | 590 | // It still has in-flight requests so should not get closed. |
| @@ -393,7 +594,7 @@ | ||
| 393 | 594 | assertThat(connection1.isClosed()).isFalse(); |
| 394 | 595 | |
| 395 | 596 | // Consume all inFlight requests on the trashed connection. |
| 396 | - completeRequests(51, requests); | |
| 597 | + MockRequest.completeMany(51, allRequests); | |
| 397 | 598 | |
| 398 | 599 | // Sleep enough time for the connection to be consider idled and closed. |
| 399 | 600 | Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS); |
| @@ -404,7 +605,7 @@ | ||
| 404 | 605 | assertThat(pool.connections).doesNotContain(connection1); |
| 405 | 606 | assertThat(pool.trash).doesNotContain(connection1); |
| 406 | 607 | } finally { |
| 407 | - completeRequests(requests); | |
| 608 | + MockRequest.completeAll(allRequests); | |
| 408 | 609 | cluster.close(); |
| 409 | 610 | } |
| 410 | 611 | } |
| @@ -420,14 +621,17 @@ | ||
| 420 | 621 | @Test(groups = "short") |
| 421 | 622 | public void should_trash_on_returning_connection_with_insufficient_streams() throws Exception { |
| 422 | 623 | Cluster cluster = createClusterBuilder().build(); |
| 423 | - List<MockRequest> requests = newArrayList(); | |
| 624 | + List<MockRequest> allRequests = newArrayList(); | |
| 424 | 625 | try { |
| 425 | 626 | HostConnectionPool pool = createPool(cluster, 1, 2); |
| 426 | 627 | Connection.Factory factory = spy(cluster.manager.connectionFactory); |
| 427 | 628 | cluster.manager.connectionFactory = factory; |
| 428 | 629 | Connection core = pool.connections.get(0); |
| 429 | 630 | |
| 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)); | |
| 431 | 635 | |
| 432 | 636 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 433 | 637 | assertThat(pool.connections).hasSize(2); |
| @@ -437,7 +641,7 @@ | ||
| 437 | 641 | pool.connections.set(1, extra1); |
| 438 | 642 | |
| 439 | 643 | // Borrow 10 times to ensure pool is utilized. |
| 440 | - requests.addAll(sendRequests(10, pool)); | |
| 644 | + allRequests.addAll(MockRequest.sendMany(10, pool)); | |
| 441 | 645 | assertThat(pool.connections).hasSize(2); |
| 442 | 646 | |
| 443 | 647 | // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams. |
| @@ -449,7 +653,7 @@ | ||
| 449 | 653 | pool.returnConnection(extra1); |
| 450 | 654 | assertThat(pool.trash).hasSize(1); |
| 451 | 655 | } finally { |
| 452 | - completeRequests(requests); | |
| 656 | + MockRequest.completeAll(allRequests); | |
| 453 | 657 | cluster.close(); |
| 454 | 658 | } |
| 455 | 659 | } |
| @@ -486,7 +690,6 @@ | ||
| 486 | 690 | } |
| 487 | 691 | } |
| 488 | 692 | |
| 489 | - | |
| 490 | 693 | /** |
| 491 | 694 | * Ensures that if all connections on a host are closed that the host is marked |
| 492 | 695 | * down and the control connection is notified of that fact and re-established |
| @@ -561,7 +764,6 @@ | ||
| 561 | 764 | } |
| 562 | 765 | } |
| 563 | 766 | |
| 564 | - | |
| 565 | 767 | /** |
| 566 | 768 | * Ensures that if a connection on a host is lost that brings the number of active connections in a pool |
| 567 | 769 | * under core connection count that up to core connections are re-established, but only after the |
| @@ -580,7 +782,7 @@ | ||
| 580 | 782 | .setConnectTimeoutMillis(readTimeout) |
| 581 | 783 | .setReadTimeoutMillis(reconnectInterval)) |
| 582 | 784 | .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build(); |
| 583 | - List<MockRequest> requests = newArrayList(); | |
| 785 | + List<MockRequest> allRequests = newArrayList(); | |
| 584 | 786 | try { |
| 585 | 787 | cluster.init(); |
| 586 | 788 | |
| @@ -608,8 +810,8 @@ | ||
| 608 | 810 | |
| 609 | 811 | // The borrowed connection should be the open one. |
| 610 | 812 | 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); | |
| 613 | 815 | |
| 614 | 816 | // Should not have tried to create a new core connection since reconnection time had not elapsed. |
| 615 | 817 | verify(factory, never()).open(any(HostConnectionPool.class)); |
| @@ -620,8 +822,8 @@ | ||
| 620 | 822 | // Attempt to borrow connection, this should trigger ensureCoreConnections thus spawning a new connection. |
| 621 | 823 | blockingExecutor.reset(); |
| 622 | 824 | request = MockRequest.send(pool); |
| 623 | - requests.add(request); | |
| 624 | - assertThat(request.connection).isEqualTo(core1); | |
| 825 | + allRequests.add(request); | |
| 826 | + assertThat(request.getConnection()).isEqualTo(core1); | |
| 625 | 827 | |
| 626 | 828 | // Should have tried to open up to core connections as result of borrowing a connection past reconnect time and not being at core. |
| 627 | 829 | blockingExecutor.blockUntilNextTaskCompleted(); |
| @@ -638,23 +840,23 @@ | ||
| 638 | 840 | |
| 639 | 841 | // Try to borrow a connection, the pool should grow. |
| 640 | 842 | blockingExecutor.reset(); |
| 641 | - requests.add(MockRequest.send(pool)); | |
| 843 | + allRequests.add(MockRequest.send(pool)); | |
| 642 | 844 | blockingExecutor.blockUntilNextTaskCompleted(); |
| 643 | 845 | verify(factory).open(any(HostConnectionPool.class)); |
| 644 | 846 | reset(factory); |
| 645 | 847 | |
| 646 | 848 | // Another core connection should be opened as result of another request to get us up to core connections. |
| 647 | 849 | blockingExecutor.reset(); |
| 648 | - requests.add(MockRequest.send(pool)); | |
| 850 | + allRequests.add(MockRequest.send(pool)); | |
| 649 | 851 | blockingExecutor.blockUntilNextTaskCompleted(); |
| 650 | 852 | verify(factory).open(any(HostConnectionPool.class)); |
| 651 | 853 | reset(factory); |
| 652 | 854 | |
| 653 | 855 | // 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)); | |
| 655 | 857 | verify(factory, after((reconnectInterval + readTimeout) * 2).never()).open(any(HostConnectionPool.class)); |
| 656 | 858 | } finally { |
| 657 | - completeRequests(requests); | |
| 859 | + MockRequest.completeAll(allRequests); | |
| 658 | 860 | cluster.close(); |
| 659 | 861 | } |
| 660 | 862 | } |
| @@ -677,7 +879,7 @@ | ||
| 677 | 879 | .setConnectTimeoutMillis(readTimeout) |
| 678 | 880 | .setReadTimeoutMillis(reconnectInterval)) |
| 679 | 881 | .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build(); |
| 680 | - List<MockRequest> requests = newArrayList(); | |
| 882 | + List<MockRequest> allRequests = newArrayList(); | |
| 681 | 883 | try { |
| 682 | 884 | cluster.init(); |
| 683 | 885 | |
| @@ -691,7 +893,7 @@ | ||
| 691 | 893 | List<MockRequest> core0requests = newArrayList(); |
| 692 | 894 | for (int i = 0; i < 101; i++) { |
| 693 | 895 | MockRequest request = MockRequest.send(pool); |
| 694 | - assertThat(request.connection).isEqualTo(core0); | |
| 896 | + assertThat(request.getConnection()).isEqualTo(core0); | |
| 695 | 897 | core0requests.add(request); |
| 696 | 898 | } |
| 697 | 899 | |
| @@ -712,13 +914,15 @@ | ||
| 712 | 914 | |
| 713 | 915 | // Since core0 was closed, all of it's requests should have errored. |
| 714 | 916 | 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); | |
| 716 | 918 | } |
| 717 | 919 | |
| 718 | 920 | assertThat(cluster).host(1).hasState(Host.State.UP); |
| 719 | 921 | |
| 720 | 922 | // 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); | |
| 722 | 926 | assertThat(pool.connections).hasSize(1); |
| 723 | 927 | |
| 724 | 928 | // A new connection should never have been spawned since we didn't max out core. |
| @@ -726,8 +930,8 @@ | ||
| 726 | 930 | |
| 727 | 931 | // Borrow another connection, since we exceed max another connection should be opened. |
| 728 | 932 | 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); | |
| 731 | 935 | |
| 732 | 936 | // After some time the a connection should attempt to be opened (but will fail). |
| 733 | 937 | verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class)); |
| @@ -745,8 +949,8 @@ | ||
| 745 | 949 | |
| 746 | 950 | // Borrow another connection, since we exceed max another connection should be opened. |
| 747 | 951 | request = MockRequest.send(pool); |
| 748 | - requests.add(request); | |
| 749 | - assertThat(request.connection).isEqualTo(extra1); | |
| 952 | + allRequests.add(request); | |
| 953 | + assertThat(request.getConnection()).isEqualTo(extra1); | |
| 750 | 954 | |
| 751 | 955 | // Wait some reasonable amount of time for connection to reestablish then check pool size. |
| 752 | 956 | Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS); |
| @@ -755,10 +959,10 @@ | ||
| 755 | 959 | |
| 756 | 960 | // Borrowed connection should be the newly spawned connection since the other one has some inflight requests. |
| 757 | 961 | 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); | |
| 760 | 964 | } finally { |
| 761 | - completeRequests(requests); | |
| 965 | + MockRequest.completeAll(allRequests); | |
| 762 | 966 | cluster.close(); |
| 763 | 967 | } |
| 764 | 968 | } |
| @@ -781,7 +985,7 @@ | ||
| 781 | 985 | .setConnectTimeoutMillis(readTimeout) |
| 782 | 986 | .setReadTimeoutMillis(reconnectInterval)) |
| 783 | 987 | .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build(); |
| 784 | - List<MockRequest> requests = newArrayList(); | |
| 988 | + List<MockRequest> allRequests = newArrayList(); | |
| 785 | 989 | try { |
| 786 | 990 | cluster.init(); |
| 787 | 991 | |
| @@ -811,13 +1015,13 @@ | ||
| 811 | 1015 | // we need to wait for connections to be established between requests for the pool |
| 812 | 1016 | // to spawn new connections (since it only allows one simultaneous creation). |
| 813 | 1017 | for (int i = 5; i <= 8; i++) { |
| 814 | - requests.add(MockRequest.send(pool)); | |
| 1018 | + allRequests.add(MockRequest.send(pool)); | |
| 815 | 1019 | verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class)); |
| 816 | 1020 | reset(factory); |
| 817 | 1021 | assertPoolSize(pool, i); |
| 818 | 1022 | } |
| 819 | 1023 | } finally { |
| 820 | - completeRequests(requests); | |
| 1024 | + MockRequest.completeAll(allRequests); | |
| 821 | 1025 | cluster.close(); |
| 822 | 1026 | } |
| 823 | 1027 | } |
| @@ -825,15 +1029,15 @@ | ||
| 825 | 1029 | /** |
| 826 | 1030 | * Ensures that if all connections fail on pool init that the host and subsequently the |
| 827 | 1031 | * 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 | |
| 829 | 1033 | * according to the ConvictionPolicy. |
| 830 | 1034 | * |
| 831 | 1035 | * @jira_ticket JAVA-544 |
| 832 | 1036 | * @test_category connection:connection_pool |
| 833 | 1037 | * @since 2.0.11 |
| 834 | 1038 | */ |
| 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() { | |
| 837 | 1041 | int readTimeout = 1000; |
| 838 | 1042 | int reconnectInterval = 1000; |
| 839 | 1043 | Cluster cluster = this.createClusterBuilder() |
| @@ -862,16 +1066,19 @@ | ||
| 862 | 1066 | assertThat(cluster).host(1).hasState(Host.State.UP); |
| 863 | 1067 | assertThat(cluster).hasOpenControlConnection(); |
| 864 | 1068 | |
| 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*/} | |
| 866 | 1074 | } finally { |
| 867 | 1075 | cluster.close(); |
| 868 | 1076 | } |
| 869 | 1077 | } |
| 870 | 1078 | |
| 871 | - | |
| 872 | 1079 | /** |
| 873 | 1080 | * 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 | |
| 875 | 1082 | * on the pool after the conviction period that all core connections are created. |
| 876 | 1083 | * |
| 877 | 1084 | * @jira_ticket JAVA-544 |
| @@ -912,12 +1119,13 @@ | ||
| 912 | 1119 | Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS); |
| 913 | 1120 | |
| 914 | 1121 | reset(factory); |
| 915 | - MockRequest request = MockRequest.send(pool); | |
| 916 | - request.simulateSuccessResponse(); | |
| 1122 | + MockRequest request = MockRequest.send(pool, 1); | |
| 917 | 1123 | |
| 918 | 1124 | // Should create up to core connections. |
| 919 | 1125 | verify(factory, timeout(readTimeout * 8).times(8)).open(any(HostConnectionPool.class)); |
| 920 | 1126 | assertPoolSize(pool, 8); |
| 1127 | + | |
| 1128 | + request.simulateSuccessResponse(); | |
| 921 | 1129 | } finally { |
| 922 | 1130 | cluster.close(); |
| 923 | 1131 | } |
| @@ -946,6 +1154,9 @@ | ||
| 946 | 1154 | cluster.init(); |
| 947 | 1155 | assertThat(cluster).hasOpenControlConnection(); |
| 948 | 1156 | |
| 1157 | + Connection.Factory factory = spy(cluster.manager.connectionFactory); | |
| 1158 | + cluster.manager.connectionFactory = factory; | |
| 1159 | + | |
| 949 | 1160 | HostConnectionPool pool = createPool(cluster, 0, 2); |
| 950 | 1161 | |
| 951 | 1162 | // Pool should be empty. |
| @@ -955,12 +1166,14 @@ | ||
| 955 | 1166 | assertThat(cluster).host(1).hasState(Host.State.UP); |
| 956 | 1167 | assertThat(cluster).hasOpenControlConnection(); |
| 957 | 1168 | |
| 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); | |
| 961 | 1171 | |
| 962 | 1172 | // Should create up to core connections. |
| 1173 | + verify(factory, timeout(readTimeout).times(1)).open(any(HostConnectionPool.class)); | |
| 963 | 1174 | assertThat(pool.connections).hasSize(1); |
| 1175 | + | |
| 1176 | + request.simulateSuccessResponse(); | |
| 964 | 1177 | } finally { |
| 965 | 1178 | cluster.close(); |
| 966 | 1179 | } |
| @@ -979,10 +1192,10 @@ | ||
| 979 | 1192 | } |
| 980 | 1193 | |
| 981 | 1194 | /** |
| 982 | - * <p> | |
| 1195 | + * <p/> | |
| 983 | 1196 | * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the |
| 984 | 1197 | * insertions are being executed, the number of opened connection is monitored. |
| 985 | - * <p> | |
| 1198 | + * <p/> | |
| 986 | 1199 | * If at anytime, the number of opened connections is negative, this test will fail. |
| 987 | 1200 | * |
| 988 | 1201 | * @jira_ticket JAVA-349 |
| @@ -1061,51 +1274,115 @@ | ||
| 1061 | 1274 | |
| 1062 | 1275 | enum State {START, COMPLETED, FAILED, TIMED_OUT} |
| 1063 | 1276 | |
| 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 | + } | |
| 1066 | 1302 | |
| 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 | + } | |
| 1068 | 1318 | |
| 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 | + } | |
| 1075 | 1326 | } |
| 1076 | 1327 | |
| 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 | + }); | |
| 1079 | 1338 | } |
| 1080 | 1339 | |
| 1081 | 1340 | void simulateSuccessResponse() { |
| 1082 | - onSet(connection, null, 0, 0); | |
| 1341 | + onSet(getConnection(), null, 0, 0); | |
| 1083 | 1342 | } |
| 1084 | 1343 | |
| 1085 | 1344 | @SuppressWarnings("unused") |
| 1086 | 1345 | void simulateErrorResponse() { |
| 1087 | - onException(connection, null, 0, 0); | |
| 1346 | + onException(getConnection(), null, 0, 0); | |
| 1088 | 1347 | } |
| 1089 | 1348 | |
| 1090 | 1349 | @SuppressWarnings("unused") |
| 1091 | 1350 | void simulateTimeout() { |
| 1092 | - if (onTimeout(connection, 0, 0)) | |
| 1351 | + if (onTimeout(getConnection(), 0, 0)) | |
| 1093 | 1352 | responseHandler.cancelHandler(); |
| 1094 | 1353 | } |
| 1095 | 1354 | |
| 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 | + | |
| 1096 | 1367 | @Override |
| 1097 | 1368 | 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 | + } | |
| 1098 | 1375 | if (state.compareAndSet(State.START, State.COMPLETED)) { |
| 1099 | - connection.release(); | |
| 1100 | 1376 | connection.dispatcher.removeHandler(responseHandler, true); |
| 1377 | + connection.release(); | |
| 1101 | 1378 | } |
| 1102 | 1379 | } |
| 1103 | 1380 | |
| 1104 | 1381 | @Override |
| 1105 | 1382 | public void onException(Connection connection, Exception exception, long latency, int retryCount) { |
| 1106 | 1383 | if (state.compareAndSet(State.START, State.FAILED)) { |
| 1107 | - connection.release(); | |
| 1108 | 1384 | connection.dispatcher.removeHandler(responseHandler, true); |
| 1385 | + connection.release(); | |
| 1109 | 1386 | } |
| 1110 | 1387 | } |
| 1111 | 1388 |
modified manual/async/README.md +0 −12
| @@ -130,21 +130,9 @@ | ||
| 130 | 130 | issues, you should create your `Cluster` instances while bootstrapping |
| 131 | 131 | your application, and call `init` immediately. If you need to create new |
| 132 | 132 | 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). | |
| 144 | 133 | * trying to read fields from a [query trace] will block if the trace |
| 145 | 134 | hasn't been fetched already. |
| 146 | 135 | |
| 147 | 136 | [ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained |
| 148 | 137 | [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- | |
| 150 | 138 | [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 @@ | ||
| 180 | 180 | message. |
| 181 | 181 | |
| 182 | 182 | |
| 183 | -#### Acquisition timeout | |
| 183 | +#### Acquisition queue | |
| 184 | 184 | |
| 185 | 185 | When the driver tries to send a request to a host, it will first try to |
| 186 | 186 | acquire a connection from this host's pool. If the pool is busy (i.e. |
| 187 | 187 | 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. | |
| 191 | 190 | |
| 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. | |
| 195 | 196 | |
| 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. | |
| 201 | 201 | |
| 202 | 202 | |
| 203 | 203 | ### Monitoring and tuning the pool |
| @@ -278,14 +278,15 @@ | ||
| 278 | 278 | [newConnectionThreshold][nct] so that enough connections are added by |
| 279 | 279 | the time you reach the bottleneck. |
| 280 | 280 | |
| 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 @@ | ||
| 3 | 3 | The purpose of this guide is to detail changes made by successive |
| 4 | 4 | versions of the Java driver. |
| 5 | 5 | |
| 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 | + | |
| 6 | 22 | ### 3.0.0 |
| 7 | 23 | |
| 8 | 24 | This version brings parity with Cassandra 2.2 and 3.0. |