kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | fa3b8ab03aa1a3e66fb6f124fd766f0bb9dd50e788d111f5ad6cf474a97fb2f3 |
|---|---|
| Author | Olivier Michallat <olim7t@users.noreply.github.com> · 2015-03-27 19:17 +01:00 |
| Committer | Olivier Michallat <olim7t@users.noreply.github.com> · 2015-03-27 19:17 +01:00 |
| Parents | 42972cf86120, 2964aed846e2 |
9 files changed
modified driver-core/CHANGELOG.rst +2 −0
| @@ -20,6 +20,8 @@ | ||
| 20 | 20 | - [improvement] Expose TokenRange#contains (JAVA-687) |
| 21 | 21 | - [new feature] Expose values of BoundStatement (JAVA-547) |
| 22 | 22 | - [new feature] Add getObject to BoundStatement and Row (JAVA-584) |
| 23 | +- [improvement] Improve connection pool resizing algorithm (JAVA-419) | |
| 24 | +- [bug] Fix race condition between pool expansion and shutdown (JAVA-599) | |
| 23 | 25 | |
| 24 | 26 | Merged from 2.0.9_fixes branch: |
| 25 | 27 |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +15 −0
| @@ -1168,6 +1168,8 @@ | ||
| 1168 | 1168 | |
| 1169 | 1169 | this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this); |
| 1170 | 1170 | this.listeners = new CopyOnWriteArraySet<Host.StateListener>(listeners); |
| 1171 | + | |
| 1172 | + this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS); | |
| 1171 | 1173 | } |
| 1172 | 1174 | |
| 1173 | 1175 | // Initialization is not too performance intensive and in practice there shouldn't be contention |
| @@ -2226,6 +2228,19 @@ | ||
| 2226 | 2228 | }).start(); |
| 2227 | 2229 | } |
| 2228 | 2230 | } |
| 2231 | + | |
| 2232 | + private class CleanupIdleConnectionsTask implements Runnable { | |
| 2233 | + @Override public void run() { | |
| 2234 | + try { | |
| 2235 | + long now = System.currentTimeMillis(); | |
| 2236 | + for (SessionManager session : sessions) { | |
| 2237 | + session.cleanupIdleConnections(now); | |
| 2238 | + } | |
| 2239 | + } catch (Exception e) { | |
| 2240 | + logger.warn("Error while trashing idle connections", e); | |
| 2241 | + } | |
| 2242 | + } | |
| 2243 | + } | |
| 2229 | 2244 | } |
| 2230 | 2245 | |
| 2231 | 2246 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +161 −50
| @@ -36,6 +36,8 @@ | ||
| 36 | 36 | |
| 37 | 37 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 38 | 38 | |
| 39 | +import static com.datastax.driver.core.PooledConnection.State.*; | |
| 40 | + | |
| 39 | 41 | class HostConnectionPool { |
| 40 | 42 | |
| 41 | 43 | private static final Logger logger = LoggerFactory.getLogger(HostConnectionPool.class); |
| @@ -53,7 +55,11 @@ | ||
| 53 | 55 | |
| 54 | 56 | final List<PooledConnection> connections; |
| 55 | 57 | private final AtomicInteger open; |
| 56 | - private final Set<Connection> trash = new CopyOnWriteArraySet<Connection>(); | |
| 58 | + /** The total number of in-flight requests on all connections of this pool. */ | |
| 59 | + final AtomicInteger totalInFlight = new AtomicInteger(); | |
| 60 | + /** The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}*/ | |
| 61 | + private final AtomicInteger maxTotalInFlight = new AtomicInteger(); | |
| 62 | + final Set<PooledConnection> trash = new CopyOnWriteArraySet<PooledConnection>(); | |
| 57 | 63 | |
| 58 | 64 | private volatile int waiter = 0; |
| 59 | 65 | private final Lock waitLock = new ReentrantLock(true); |
| @@ -63,6 +69,7 @@ | ||
| 63 | 69 | |
| 64 | 70 | private final AtomicInteger scheduledForCreation = new AtomicInteger(); |
| 65 | 71 | |
| 72 | + private volatile boolean isClosing; | |
| 66 | 73 | private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>(); |
| 67 | 74 | |
| 68 | 75 | public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException { |
| @@ -132,6 +139,7 @@ | ||
| 132 | 139 | manager.blockingExecutor().submit(newConnectionTask); |
| 133 | 140 | } |
| 134 | 141 | PooledConnection c = waitForConnection(timeout, unit); |
| 142 | + totalInFlight.incrementAndGet(); | |
| 135 | 143 | c.setKeyspace(manager.poolsState.keyspace); |
| 136 | 144 | return c; |
| 137 | 145 | } |
| @@ -146,9 +154,6 @@ | ||
| 146 | 154 | } |
| 147 | 155 | } |
| 148 | 156 | |
| 149 | - if (minInFlight >= options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance) && connections.size() < options().getMaxConnectionsPerHost(hostDistance)) | |
| 150 | - maybeSpawnNewConnection(); | |
| 151 | - | |
| 152 | 157 | if (leastBusy == null) { |
| 153 | 158 | // We could have raced with a shutdown since the last check |
| 154 | 159 | if (isClosed()) |
| @@ -170,6 +175,24 @@ | ||
| 170 | 175 | break; |
| 171 | 176 | } |
| 172 | 177 | } |
| 178 | + | |
| 179 | + int totalInFlightCount = totalInFlight.incrementAndGet(); | |
| 180 | + // update max atomically: | |
| 181 | + while (true) { | |
| 182 | + int oldMax = maxTotalInFlight.get(); | |
| 183 | + if (totalInFlightCount <= oldMax || maxTotalInFlight.compareAndSet(oldMax, totalInFlightCount)) | |
| 184 | + break; | |
| 185 | + } | |
| 186 | + | |
| 187 | + int connectionCount = open.get() + scheduledForCreation.get(); | |
| 188 | + if (connectionCount < options().getMaxConnectionsPerHost(hostDistance)) { | |
| 189 | + // Add a connection if we fill the first n-1 connections and almost fill the last one | |
| 190 | + int currentCapacity = (connectionCount - 1) * StreamIdGenerator.MAX_STREAM_PER_CONNECTION | |
| 191 | + + options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance); | |
| 192 | + if (totalInFlightCount > currentCapacity) | |
| 193 | + maybeSpawnNewConnection(); | |
| 194 | + } | |
| 195 | + | |
| 173 | 196 | leastBusy.setKeyspace(manager.poolsState.keyspace); |
| 174 | 197 | return leastBusy; |
| 175 | 198 | } |
| @@ -260,7 +283,8 @@ | ||
| 260 | 283 | } |
| 261 | 284 | |
| 262 | 285 | public void returnConnection(PooledConnection connection) { |
| 263 | - int inFlight = connection.inFlight.decrementAndGet(); | |
| 286 | + connection.inFlight.decrementAndGet(); | |
| 287 | + totalInFlight.decrementAndGet(); | |
| 264 | 288 | |
| 265 | 289 | if (isClosed()) { |
| 266 | 290 | close(connection); |
| @@ -273,13 +297,8 @@ | ||
| 273 | 297 | return; |
| 274 | 298 | } |
| 275 | 299 | |
| 276 | - if (trash.contains(connection)) { | |
| 277 | - if (inFlight == 0 && trash.remove(connection)) | |
| 278 | - close(connection); | |
| 279 | - } else { | |
| 280 | - if (connections.size() > options().getCoreConnectionsPerHost(hostDistance) && inFlight <= options().getMinSimultaneousRequestsPerConnectionThreshold(hostDistance)) { | |
| 281 | - trashConnection(connection); | |
| 282 | - } else if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) { | |
| 300 | + if (connection.state.get() != TRASHED) { | |
| 301 | + if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) { | |
| 283 | 302 | replaceConnection(connection); |
| 284 | 303 | } else { |
| 285 | 304 | signalAvailableConnection(); |
| @@ -290,44 +309,38 @@ | ||
| 290 | 309 | // Trash the connection and create a new one, but we don't call trashConnection |
| 291 | 310 | // directly because we want to make sure the connection is always trashed. |
| 292 | 311 | private void replaceConnection(PooledConnection connection) { |
| 293 | - if (connection.markForTrash.compareAndSet(false, true)) | |
| 294 | - open.decrementAndGet(); | |
| 312 | + if (!connection.state.compareAndSet(OPEN, TRASHED)) | |
| 313 | + return; | |
| 314 | + open.decrementAndGet(); | |
| 295 | 315 | maybeSpawnNewConnection(); |
| 316 | + connection.maxIdleTime = Long.MIN_VALUE; | |
| 296 | 317 | doTrashConnection(connection); |
| 297 | 318 | } |
| 298 | 319 | |
| 299 | 320 | private boolean trashConnection(PooledConnection connection) { |
| 300 | - if (connection.markForTrash.compareAndSet(false, true)) { | |
| 301 | - // First, make sure we don't go below core connections | |
| 302 | - for (;;) { | |
| 303 | - int opened = open.get(); | |
| 304 | - if (opened <= options().getCoreConnectionsPerHost(hostDistance)) { | |
| 305 | - connection.markForTrash.set(false); | |
| 306 | - return false; | |
| 307 | - } | |
| 321 | + if (!connection.state.compareAndSet(OPEN, TRASHED)) | |
| 322 | + return true; | |
| 308 | 323 | |
| 309 | - if (open.compareAndSet(opened, opened - 1)) | |
| 310 | - break; | |
| 324 | + // First, make sure we don't go below core connections | |
| 325 | + for (;;) { | |
| 326 | + int opened = open.get(); | |
| 327 | + if (opened <= options().getCoreConnectionsPerHost(hostDistance)) { | |
| 328 | + connection.state.set(OPEN); | |
| 329 | + return false; | |
| 311 | 330 | } |
| 312 | 331 | |
| 313 | - doTrashConnection(connection); | |
| 314 | - } | |
| 315 | - // If compareAndSet failed, it means we raced and another thread will execute doTrashConnection. | |
| 316 | - // If the connection needs to be closed (inFlight == 0), we don't need to do it here because the other thread will necessarily do | |
| 317 | - // it: | |
| 318 | - // - the current thread decremented inFlight in returnConnection | |
| 319 | - // - we know it did it before the connection was trashed, because otherwise it would have entered `if (trash.contains(connection))` | |
| 320 | - // in returnConnection and not arrived here. | |
| 321 | - // - so the other thread will see the up-to-date value of inFlight and take appropriate action. | |
| 332 | + if (open.compareAndSet(opened, opened - 1)) | |
| 333 | + break; | |
| 334 | + } | |
| 335 | + logger.trace("Trashing {}", connection); | |
| 336 | + connection.maxIdleTime = System.currentTimeMillis() + options().getIdleTimeoutSeconds() * 1000; | |
| 337 | + doTrashConnection(connection); | |
| 322 | 338 | return true; |
| 323 | 339 | } |
| 324 | 340 | |
| 325 | 341 | private void doTrashConnection(PooledConnection connection) { |
| 326 | - trash.add(connection); | |
| 327 | 342 | connections.remove(connection); |
| 328 | - | |
| 329 | - if (connection.inFlight.get() == 0 && trash.remove(connection)) | |
| 330 | - close(connection); | |
| 343 | + trash.add(connection); | |
| 331 | 344 | } |
| 332 | 345 | |
| 333 | 346 | private boolean addConnectionIfUnderMaximum() { |
| @@ -342,14 +355,29 @@ | ||
| 342 | 355 | break; |
| 343 | 356 | } |
| 344 | 357 | |
| 345 | - if (isClosed()) { | |
| 358 | + if (isClosing) { | |
| 346 | 359 | open.decrementAndGet(); |
| 347 | 360 | return false; |
| 348 | 361 | } |
| 349 | 362 | |
| 350 | 363 | // Now really open the connection |
| 351 | 364 | try { |
| 352 | - connections.add(manager.connectionFactory().open(this)); | |
| 365 | + PooledConnection newConnection = tryResurrectFromTrash(); | |
| 366 | + if (newConnection == null) { | |
| 367 | + logger.debug("Creating new connection on busy pool to {}", host); | |
| 368 | + newConnection = manager.connectionFactory().open(this); | |
| 369 | + } | |
| 370 | + connections.add(newConnection); | |
| 371 | + | |
| 372 | + newConnection.state.compareAndSet(RESURRECTING, OPEN); // no-op if it was already OPEN | |
| 373 | + | |
| 374 | + // We might have raced with pool shutdown since the last check; ensure the connection gets closed in case the pool did not do it. | |
| 375 | + if (isClosing && !newConnection.isClosed()) { | |
| 376 | + close(newConnection); | |
| 377 | + open.decrementAndGet(); | |
| 378 | + return false; | |
| 379 | + } | |
| 380 | + | |
| 353 | 381 | signalAvailableConnection(); |
| 354 | 382 | return true; |
| 355 | 383 | } catch (InterruptedException e) { |
| @@ -378,6 +406,27 @@ | ||
| 378 | 406 | } |
| 379 | 407 | } |
| 380 | 408 | |
| 409 | + private PooledConnection tryResurrectFromTrash() { | |
| 410 | + long highestMaxIdleTime = System.currentTimeMillis(); | |
| 411 | + PooledConnection chosen = null; | |
| 412 | + | |
| 413 | + while (true) { | |
| 414 | + for (PooledConnection connection : trash) | |
| 415 | + if (connection.maxIdleTime > highestMaxIdleTime && connection.maxAvailableStreams() > MIN_AVAILABLE_STREAMS) { | |
| 416 | + chosen = connection; | |
| 417 | + highestMaxIdleTime = connection.maxIdleTime; | |
| 418 | + } | |
| 419 | + | |
| 420 | + if (chosen == null) | |
| 421 | + return null; | |
| 422 | + else if (chosen.state.compareAndSet(TRASHED, RESURRECTING)) | |
| 423 | + break; | |
| 424 | + } | |
| 425 | + logger.trace("Resurrecting {}", chosen); | |
| 426 | + trash.remove(chosen); | |
| 427 | + return chosen; | |
| 428 | + } | |
| 429 | + | |
| 381 | 430 | private void maybeSpawnNewConnection() { |
| 382 | 431 | while (true) { |
| 383 | 432 | int inCreation = scheduledForCreation.get(); |
| @@ -387,21 +436,71 @@ | ||
| 387 | 436 | break; |
| 388 | 437 | } |
| 389 | 438 | |
| 390 | - logger.debug("Creating new connection on busy pool to {}", host); | |
| 391 | 439 | manager.blockingExecutor().submit(newConnectionTask); |
| 392 | 440 | } |
| 393 | 441 | |
| 394 | 442 | void replaceDefunctConnection(final PooledConnection connection) { |
| 395 | - if (connection.markForTrash.compareAndSet(false, true)) | |
| 443 | + if (connection.state.compareAndSet(OPEN, GONE)) | |
| 396 | 444 | open.decrementAndGet(); |
| 397 | - connections.remove(connection); | |
| 445 | + if (connections.remove(connection)) | |
| 446 | + manager.blockingExecutor().submit(new Runnable() { | |
| 447 | + @Override | |
| 448 | + public void run() { | |
| 449 | + addConnectionIfUnderMaximum(); | |
| 450 | + } | |
| 451 | + }); | |
| 398 | 452 | connection.closeAsync(); |
| 399 | - manager.blockingExecutor().submit(new Runnable() { | |
| 400 | - @Override | |
| 401 | - public void run() { | |
| 402 | - addConnectionIfUnderMaximum(); | |
| 453 | + } | |
| 454 | + | |
| 455 | + void cleanupIdleConnections(long now) { | |
| 456 | + if (isClosed()) | |
| 457 | + return; | |
| 458 | + | |
| 459 | + shrinkIfBelowCapacity(); | |
| 460 | + cleanupTrash(now); | |
| 461 | + } | |
| 462 | + | |
| 463 | + /** If we have more active connections than needed, trash some of them */ | |
| 464 | + private void shrinkIfBelowCapacity() { | |
| 465 | + int currentLoad = maxTotalInFlight.getAndSet(totalInFlight.get()); | |
| 466 | + | |
| 467 | + int needed = currentLoad / StreamIdGenerator.MAX_STREAM_PER_CONNECTION + 1; | |
| 468 | + if (currentLoad % StreamIdGenerator.MAX_STREAM_PER_CONNECTION > options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance)) | |
| 469 | + needed += 1; | |
| 470 | + needed = Math.max(needed, options().getCoreConnectionsPerHost(hostDistance)); | |
| 471 | + int actual = open.get(); | |
| 472 | + int toTrash = Math.max(0, actual - needed); | |
| 473 | + | |
| 474 | + logger.trace("Current inFlight = {}, {} connections needed, {} connections available, trashing {}", | |
| 475 | + currentLoad, needed, actual, toTrash); | |
| 476 | + | |
| 477 | + if (toTrash <= 0) | |
| 478 | + return; | |
| 479 | + | |
| 480 | + for (PooledConnection connection : connections) | |
| 481 | + if (trashConnection(connection)) { | |
| 482 | + toTrash -= 1; | |
| 483 | + if (toTrash == 0) | |
| 484 | + return; | |
| 485 | + } | |
| 486 | + } | |
| 487 | + | |
| 488 | + /** Close connections that have been sitting in the trash for too long */ | |
| 489 | + private void cleanupTrash(long now) { | |
| 490 | + for (PooledConnection connection : trash) { | |
| 491 | + if (connection.maxIdleTime < now && connection.state.compareAndSet(TRASHED, GONE)) { | |
| 492 | + if (connection.inFlight.get() == 0) { | |
| 493 | + logger.trace("Cleaning up {}", connection); | |
| 494 | + trash.remove(connection); | |
| 495 | + close(connection); | |
| 496 | + } else { | |
| 497 | + // Given that idleTimeout >> request timeout, all outstanding requests should | |
| 498 | + // have finished by now, so we should not get here. | |
| 499 | + // Restore the status so that it's retried on the next cleanup. | |
| 500 | + connection.state.set(TRASHED); | |
| 501 | + } | |
| 403 | 502 | } |
| 404 | - }); | |
| 503 | + } | |
| 405 | 504 | } |
| 406 | 505 | |
| 407 | 506 | private void close(final Connection connection) { |
| @@ -418,7 +517,9 @@ | ||
| 418 | 517 | if (future != null) |
| 419 | 518 | return future; |
| 420 | 519 | |
| 421 | - // Wake up all threads that waits | |
| 520 | + isClosing = true; | |
| 521 | + | |
| 522 | + // Wake up all threads that wait | |
| 422 | 523 | signalAllAvailableConnection(); |
| 423 | 524 | |
| 424 | 525 | future = new CloseFuture.Forwarding(discardAvailableConnections()); |
| @@ -432,22 +533,32 @@ | ||
| 432 | 533 | return open.get(); |
| 433 | 534 | } |
| 434 | 535 | |
| 536 | + public int trashed() { | |
| 537 | + return trash.size(); | |
| 538 | + } | |
| 539 | + | |
| 435 | 540 | private List<CloseFuture> discardAvailableConnections() { |
| 436 | 541 | // This can happen if creating the connections in the constructor fails |
| 437 | 542 | if (connections == null) |
| 438 | 543 | return Lists.newArrayList(CloseFuture.immediateFuture()); |
| 439 | 544 | |
| 440 | - List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size()); | |
| 545 | + List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size()); | |
| 546 | + | |
| 441 | 547 | for (final PooledConnection connection : connections) { |
| 442 | 548 | CloseFuture future = connection.closeAsync(); |
| 443 | 549 | future.addListener(new Runnable() { |
| 444 | 550 | public void run() { |
| 445 | - if (connection.markForTrash.compareAndSet(false, true)) | |
| 551 | + if (connection.state.compareAndSet(OPEN, GONE)) | |
| 446 | 552 | open.decrementAndGet(); |
| 447 | 553 | } |
| 448 | 554 | }, MoreExecutors.sameThreadExecutor()); |
| 449 | 555 | futures.add(future); |
| 450 | 556 | } |
| 557 | + | |
| 558 | + // Some connections in the trash might still be open if they hadn't reached their idle timeout | |
| 559 | + for (PooledConnection connection : trash) | |
| 560 | + futures.add(connection.closeAsync()); | |
| 561 | + | |
| 451 | 562 | return futures; |
| 452 | 563 | } |
| 453 | 564 |
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +24 −0
| @@ -69,6 +69,16 @@ | ||
| 69 | 69 | return value; |
| 70 | 70 | } |
| 71 | 71 | }); |
| 72 | + private final Gauge<Integer> trashedConnections = registry.register("trashed-connections", new Gauge<Integer>() { | |
| 73 | + @Override | |
| 74 | + public Integer getValue() { | |
| 75 | + int value = 0; | |
| 76 | + for (SessionManager session : manager.sessions) | |
| 77 | + for (HostConnectionPool pool : session.pools.values()) | |
| 78 | + value += pool.trashed(); | |
| 79 | + return value; | |
| 80 | + } | |
| 81 | + }); | |
| 72 | 82 | |
| 73 | 83 | private final Gauge<Integer> executorQueueDepth = registry.register("executor-queue-depth", new Gauge<Integer>() { |
| 74 | 84 | @Override |
| @@ -205,6 +215,20 @@ | ||
| 205 | 215 | return openConnections; |
| 206 | 216 | } |
| 207 | 217 | |
| 218 | + /** | |
| 219 | + * Returns the total number of currently "trashed" connections to Cassandra hosts. | |
| 220 | + * <p> | |
| 221 | + * When the load to a host decreases, the driver will reclaim some connections in order to save | |
| 222 | + * resources. No requests are sent to these connections anymore, but they are kept open for an | |
| 223 | + * additional amount of time ({@link PoolingOptions#getIdleTimeoutSeconds()}), in case the load | |
| 224 | + * goes up again. This metric counts connections in that state. | |
| 225 | + * | |
| 226 | + * @return The total number of currently trashed connections to Cassandra hosts. | |
| 227 | + */ | |
| 228 | + public Gauge<Integer> getTrashedConnections() { | |
| 229 | + return trashedConnections; | |
| 230 | + } | |
| 231 | + | |
| 208 | 232 | /** |
| 209 | 233 | * @return The number of queued up tasks in the non-blocking executor (Cassandra Java Driver workers). |
| 210 | 234 | */ |
modified driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +6 −3
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import java.net.InetSocketAddress; |
| 19 | -import java.util.concurrent.atomic.AtomicBoolean; | |
| 19 | +import java.util.concurrent.atomic.AtomicReference; | |
| 20 | 20 | |
| 21 | 21 | /** |
| 22 | 22 | * A connection that is associated to a pool. |
| @@ -25,8 +25,11 @@ | ||
| 25 | 25 | |
| 26 | 26 | final HostConnectionPool pool; |
| 27 | 27 | |
| 28 | - /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */ | |
| 29 | - final AtomicBoolean markForTrash = new AtomicBoolean(); | |
| 28 | + enum State {OPEN, TRASHED, RESURRECTING, GONE } | |
| 29 | + | |
| 30 | + final AtomicReference<State> state = new AtomicReference<State>(State.OPEN); | |
| 31 | + | |
| 32 | + volatile long maxIdleTime; | |
| 30 | 33 | |
| 31 | 34 | PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { |
| 32 | 35 | super(name, address, factory); |
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +39 −36
| @@ -31,43 +31,36 @@ | ||
| 31 | 31 | * more connections are created up to the configurable maximum number of |
| 32 | 32 | * connections ({@link #getMaxConnectionsPerHost}). When the pool exceeds |
| 33 | 33 | * the maximum number of connections, connections in excess are |
| 34 | - * reclaimed if the use of opened connections drops below the | |
| 35 | - * configured threshold ({@link #getMinSimultaneousRequestsPerConnectionThreshold}). | |
| 34 | + * reclaimed. | |
| 36 | 35 | * <p> |
| 37 | 36 | * Each of these parameters can be separately set for {@code LOCAL} and |
| 38 | 37 | * {@code REMOTE} hosts ({@link HostDistance}). For {@code IGNORED} hosts, |
| 39 | 38 | * the default for all those settings is 0 and cannot be changed. |
| 40 | - * <p> | |
| 41 | - * Due to known issues with the current pool implementation (see | |
| 42 | - * <a href="https://datastax-oss.atlassian.net/browse/JAVA-419">JAVA-419</a>), | |
| 43 | - * it is <b>strongly recommended</b> to use a fixed-size pool (core connections = | |
| 44 | - * max connections). | |
| 45 | - * The default values respect this (8 for local hosts, 2 for remote hosts). | |
| 46 | 39 | */ |
| 47 | 40 | public class PoolingOptions { |
| 48 | 41 | |
| 49 | 42 | // Note: we could use an enumMap or similar, but synchronization would |
| 50 | 43 | // be more costly so let's stick to volatile in for now. |
| 51 | - private static final int DEFAULT_MIN_REQUESTS = 25; | |
| 52 | 44 | private static final int DEFAULT_MAX_REQUESTS = 100; |
| 53 | 45 | |
| 54 | - private static final int DEFAULT_CORE_POOL_LOCAL = 8; | |
| 55 | - private static final int DEFAULT_CORE_POOL_REMOTE = 2; | |
| 46 | + private static final int DEFAULT_CORE_POOL_LOCAL = 2; | |
| 47 | + private static final int DEFAULT_CORE_POOL_REMOTE = 1; | |
| 56 | 48 | |
| 57 | 49 | private static final int DEFAULT_MAX_POOL_LOCAL = 8; |
| 58 | 50 | private static final int DEFAULT_MAX_POOL_REMOTE = 2; |
| 59 | 51 | |
| 52 | + private static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120; | |
| 60 | 53 | private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000; |
| 61 | 54 | private static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30; |
| 62 | 55 | |
| 63 | 56 | private volatile Cluster.Manager manager; |
| 64 | 57 | |
| 65 | - private final int[] minSimultaneousRequests = new int[]{ DEFAULT_MIN_REQUESTS, DEFAULT_MIN_REQUESTS, 0 }; | |
| 66 | 58 | private final int[] maxSimultaneousRequests = new int[]{ DEFAULT_MAX_REQUESTS, DEFAULT_MAX_REQUESTS, 0 }; |
| 67 | 59 | |
| 68 | 60 | private final int[] coreConnections = new int[] { DEFAULT_CORE_POOL_LOCAL, DEFAULT_CORE_POOL_REMOTE, 0 }; |
| 69 | 61 | private final int[] maxConnections = new int[] { DEFAULT_MAX_POOL_LOCAL , DEFAULT_MAX_POOL_REMOTE, 0 }; |
| 70 | 62 | |
| 63 | + private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS; | |
| 71 | 64 | private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS; |
| 72 | 65 | private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS; |
| 73 | 66 | |
| @@ -91,9 +84,12 @@ | ||
| 91 | 84 | * |
| 92 | 85 | * @param distance the {@code HostDistance} for which to return this threshold. |
| 93 | 86 | * @return the configured threshold, or the default one if none have been set. |
| 87 | + * | |
| 88 | + * @deprecated this option isn't used anymore with the current pool resizing algorithm. | |
| 94 | 89 | */ |
| 90 | + @Deprecated | |
| 95 | 91 | public int getMinSimultaneousRequestsPerConnectionThreshold(HostDistance distance) { |
| 96 | - return minSimultaneousRequests[distance.ordinal()]; | |
| 92 | + return 0; | |
| 97 | 93 | } |
| 98 | 94 | |
| 99 | 95 | /** |
| @@ -106,14 +102,11 @@ | ||
| 106 | 102 | * |
| 107 | 103 | * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED}, or if {@code minSimultaneousRequests} |
| 108 | 104 | * is not in range, or if {@code newMinSimultaneousRequests} is greater than the maximum value for this distance. |
| 105 | + * | |
| 106 | + * @deprecated this option isn't used anymore with the current pool resizing algorithm. | |
| 109 | 107 | */ |
| 108 | + @Deprecated | |
| 110 | 109 | public synchronized PoolingOptions setMinSimultaneousRequestsPerConnectionThreshold(HostDistance distance, int newMinSimultaneousRequests) { |
| 111 | - if (distance == HostDistance.IGNORED) | |
| 112 | - throw new IllegalArgumentException("Cannot set min simultaneous requests per connection threshold for " + distance + " hosts"); | |
| 113 | - | |
| 114 | - checkRequestsPerConnectionRange(newMinSimultaneousRequests, "Min simultaneous requests per connection", distance); | |
| 115 | - checkRequestsPerConnectionOrder(newMinSimultaneousRequests, maxSimultaneousRequests[distance.ordinal()], distance); | |
| 116 | - minSimultaneousRequests[distance.ordinal()] = newMinSimultaneousRequests; | |
| 117 | 110 | return this; |
| 118 | 111 | } |
| 119 | 112 | |
| @@ -156,7 +149,6 @@ | ||
| 156 | 149 | throw new IllegalArgumentException("Cannot set max simultaneous requests per connection threshold for " + distance + " hosts"); |
| 157 | 150 | |
| 158 | 151 | checkRequestsPerConnectionRange(newMaxSimultaneousRequests, "Max simultaneous requests per connection", distance); |
| 159 | - checkRequestsPerConnectionOrder(minSimultaneousRequests[distance.ordinal()], newMaxSimultaneousRequests, distance); | |
| 160 | 152 | maxSimultaneousRequests[distance.ordinal()] = newMaxSimultaneousRequests; |
| 161 | 153 | return this; |
| 162 | 154 | } |
| @@ -177,11 +169,6 @@ | ||
| 177 | 169 | |
| 178 | 170 | /** |
| 179 | 171 | * Sets the core number of connections per host. |
| 180 | - * <p> | |
| 181 | - * Due to known issues with the current pool implementation (see | |
| 182 | - * <a href="https://datastax-oss.atlassian.net/browse/JAVA-419">JAVA-419</a>), | |
| 183 | - * it is <b>strongly recommended</b> to use a fixed-size pool (core connections = | |
| 184 | - * max connections). | |
| 185 | 172 | * |
| 186 | 173 | * @param distance the {@code HostDistance} for which to set this threshold. |
| 187 | 174 | * @param newCoreConnections the value to set |
| @@ -217,11 +204,6 @@ | ||
| 217 | 204 | |
| 218 | 205 | /** |
| 219 | 206 | * Sets the maximum number of connections per host. |
| 220 | - * <p> | |
| 221 | - * Due to known issues with the current pool implementation (see | |
| 222 | - * <a href="https://datastax-oss.atlassian.net/browse/JAVA-419">JAVA-419</a>), | |
| 223 | - * it is <b>strongly recommended</b> to use a fixed-size pool (core connections = | |
| 224 | - * max connections). | |
| 225 | 207 | * |
| 226 | 208 | * @param distance the {@code HostDistance} for which to set this threshold. |
| 227 | 209 | * @param newMaxConnections the value to set |
| @@ -239,6 +221,33 @@ | ||
| 239 | 221 | return this; |
| 240 | 222 | } |
| 241 | 223 | |
| 224 | + /** | |
| 225 | + * Returns the timeout before an idle connection is removed. | |
| 226 | + * | |
| 227 | + * @return the timeout. | |
| 228 | + */ | |
| 229 | + public int getIdleTimeoutSeconds() { | |
| 230 | + return idleTimeoutSeconds; | |
| 231 | + } | |
| 232 | + | |
| 233 | + /** | |
| 234 | + * Sets the timeout before an idle connection is removed. | |
| 235 | + * <p> | |
| 236 | + * The order of magnitude should be a few minutes (the default is 120 seconds). The | |
| 237 | + * timeout that triggers the removal has a granularity of 10 seconds. | |
| 238 | + * | |
| 239 | + * @param idleTimeoutSeconds the new timeout in seconds. | |
| 240 | + * @return this {@code PoolingOptions}. | |
| 241 | + * | |
| 242 | + * @throws IllegalArgumentException if the timeout is negative. | |
| 243 | + */ | |
| 244 | + public PoolingOptions setIdleTimeoutSeconds(int idleTimeoutSeconds) { | |
| 245 | + if (idleTimeoutSeconds < 0) | |
| 246 | + throw new IllegalArgumentException("Idle timeout must be positive"); | |
| 247 | + this.idleTimeoutSeconds = idleTimeoutSeconds; | |
| 248 | + return this; | |
| 249 | + } | |
| 250 | + | |
| 242 | 251 | /** |
| 243 | 252 | * Returns the timeout when trying to acquire a connection from a host's pool. |
| 244 | 253 | * |
| @@ -326,12 +335,6 @@ | ||
| 326 | 335 | StreamIdGenerator.MAX_STREAM_PER_CONNECTION)); |
| 327 | 336 | } |
| 328 | 337 | |
| 329 | - private static void checkRequestsPerConnectionOrder(int min, int max, HostDistance distance) { | |
| 330 | - if (min > max) | |
| 331 | - throw new IllegalArgumentException(String.format("Min simultaneous requests per connection for %s hosts must be less than max (%d > %d)", | |
| 332 | - distance, min, max)); | |
| 333 | - } | |
| 334 | - | |
| 335 | 338 | private static void checkConnectionsPerHostOrder(int core, int max, HostDistance distance) { |
| 336 | 339 | if (core > max) |
| 337 | 340 | throw new IllegalArgumentException(String.format("Core connections for %s hosts must be less than max (%d > %d)", |
modified driver-core/src/main/java/com/datastax/driver/core/Session.java +17 −1
| @@ -17,7 +17,6 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.io.Closeable; |
| 19 | 19 | import java.util.Collection; |
| 20 | -import java.util.Map; | |
| 21 | 20 | |
| 22 | 21 | import com.google.common.util.concurrent.ListenableFuture; |
| 23 | 22 | |
| @@ -376,6 +375,9 @@ | ||
| 376 | 375 | |
| 377 | 376 | /** |
| 378 | 377 | * The number of open connections to a given host. |
| 378 | + * <p> | |
| 379 | + * Note that this refers to <em>active</em> connections. The actual number of connections also | |
| 380 | + * includes {@link #getTrashedConnections(Host)}. | |
| 379 | 381 | * |
| 380 | 382 | * @param host the host to get open connections for. |
| 381 | 383 | * @return The number of open connections to {@code host}. If the session |
| @@ -383,6 +385,20 @@ | ||
| 383 | 385 | */ |
| 384 | 386 | public int getOpenConnections(Host host); |
| 385 | 387 | |
| 388 | + /** | |
| 389 | + * The number of "trashed" connections to a given host. | |
| 390 | + * <p> | |
| 391 | + * When the load to a host decreases, the driver will reclaim some connections in order to save | |
| 392 | + * resources. No requests are sent to these connections anymore, but they are kept open for an | |
| 393 | + * additional amount of time ({@link PoolingOptions#getIdleTimeoutSeconds()}), in case the load | |
| 394 | + * goes up again. This method counts connections in that state. | |
| 395 | + * | |
| 396 | + * @param host the host to get trashed connections for. | |
| 397 | + * @return The number of trashed connections to {@code host}. If the session | |
| 398 | + * is not connected to that host, 0 is returned. | |
| 399 | + */ | |
| 400 | + public int getTrashedConnections(Host host); | |
| 401 | + | |
| 386 | 402 | /** |
| 387 | 403 | * The number of queries that are currently being executed though a given host. |
| 388 | 404 | * <p> |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +16 −3
| @@ -556,11 +556,18 @@ | ||
| 556 | 556 | return future; |
| 557 | 557 | } |
| 558 | 558 | |
| 559 | + void cleanupIdleConnections(long now) { | |
| 560 | + for (HostConnectionPool pool : pools.values()) { | |
| 561 | + pool.cleanupIdleConnections(now); | |
| 562 | + } | |
| 563 | + } | |
| 564 | + | |
| 559 | 565 | private static class State implements Session.State { |
| 560 | 566 | |
| 561 | 567 | private final SessionManager session; |
| 562 | 568 | private final List<Host> connectedHosts; |
| 563 | 569 | private final int[] openConnections; |
| 570 | + private final int[] trashedConnections; | |
| 564 | 571 | private final int[] inFlightQueries; |
| 565 | 572 | |
| 566 | 573 | private State(SessionManager session) { |
| @@ -568,6 +575,7 @@ | ||
| 568 | 575 | this.connectedHosts = ImmutableList.copyOf(session.pools.keySet()); |
| 569 | 576 | |
| 570 | 577 | this.openConnections = new int[connectedHosts.size()]; |
| 578 | + this.trashedConnections = new int[connectedHosts.size()]; | |
| 571 | 579 | this.inFlightQueries = new int[connectedHosts.size()]; |
| 572 | 580 | |
| 573 | 581 | int i = 0; |
| @@ -578,14 +586,14 @@ | ||
| 578 | 586 | // connections will be slightly weird, but it's unlikely enough that we don't bother avoiding. |
| 579 | 587 | if (p == null) { |
| 580 | 588 | openConnections[i] = 0; |
| 589 | + trashedConnections[i] = 0; | |
| 581 | 590 | inFlightQueries[i] = 0; |
| 582 | 591 | continue; |
| 583 | 592 | } |
| 584 | 593 | |
| 585 | 594 | openConnections[i] = p.connections.size(); |
| 586 | - for (Connection c : p.connections) { | |
| 587 | - inFlightQueries[i] += c.inFlight.get(); | |
| 588 | - } | |
| 595 | + trashedConnections[i] = p.trash.size(); | |
| 596 | + inFlightQueries[i] = p.totalInFlight.get(); | |
| 589 | 597 | i++; |
| 590 | 598 | } |
| 591 | 599 | } |
| @@ -616,6 +624,11 @@ | ||
| 616 | 624 | return i < 0 ? 0 : openConnections[i]; |
| 617 | 625 | } |
| 618 | 626 | |
| 627 | + public int getTrashedConnections(Host host) { | |
| 628 | + int i = getIdx(host); | |
| 629 | + return i < 0 ? 0 : trashedConnections[i]; | |
| 630 | + } | |
| 631 | + | |
| 619 | 632 | public int getInFlightQueries(Host host) { |
| 620 | 633 | int i = getIdx(host); |
| 621 | 634 | return i < 0 ? 0 : inFlightQueries[i]; |
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +324 −11
| @@ -1,17 +1,20 @@ | ||
| 1 | 1 | package com.datastax.driver.core; |
| 2 | 2 | |
| 3 | -import com.codahale.metrics.Gauge; | |
| 4 | -import com.google.common.collect.Lists; | |
| 5 | -import org.testng.annotations.Test; | |
| 6 | - | |
| 7 | 3 | import java.util.Collection; |
| 8 | -import java.util.concurrent.CountDownLatch; | |
| 9 | -import java.util.concurrent.ExecutorService; | |
| 10 | -import java.util.concurrent.Executors; | |
| 11 | -import java.util.concurrent.ScheduledExecutorService; | |
| 4 | +import java.util.List; | |
| 5 | +import java.util.concurrent.*; | |
| 12 | 6 | import java.util.concurrent.atomic.AtomicBoolean; |
| 13 | 7 | |
| 8 | +import static java.util.concurrent.TimeUnit.MILLISECONDS; | |
| 14 | 9 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 10 | + | |
| 11 | +import com.codahale.metrics.Gauge; | |
| 12 | +import com.google.common.collect.Lists; | |
| 13 | +import org.testng.annotations.Test; | |
| 14 | + | |
| 15 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 16 | +import static org.mockito.Mockito.doReturn; | |
| 17 | +import static org.mockito.Mockito.spy; | |
| 15 | 18 | import static org.testng.Assert.fail; |
| 16 | 19 | |
| 17 | 20 | public class HostConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster { |
| @@ -25,16 +28,326 @@ | ||
| 25 | 28 | return Lists.newArrayList(sb.toString()); |
| 26 | 29 | } |
| 27 | 30 | |
| 31 | + /** | |
| 32 | + * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead | |
| 33 | + * of creating a new connection. | |
| 34 | + * | |
| 35 | + * @since 2.0.10, 2.1.6 | |
| 36 | + * @jira_ticket JAVA-419 | |
| 37 | + * @test_category connection:connection_pool | |
| 38 | + */ | |
| 39 | + @Test(groups = "short") | |
| 40 | + public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException { | |
| 41 | + HostConnectionPool pool = createPool(2, 2); | |
| 42 | + | |
| 43 | + assertThat(pool.connections.size()).isEqualTo(2); | |
| 44 | + List<PooledConnection> coreConnections = Lists.newArrayList(pool.connections); | |
| 45 | + | |
| 46 | + for (int i = 0; i < 256; i++) { | |
| 47 | + PooledConnection connection = pool.borrowConnection(100, MILLISECONDS); | |
| 48 | + assertThat(coreConnections).contains(connection); | |
| 49 | + } | |
| 50 | + | |
| 51 | + boolean timedOut = false; | |
| 52 | + try { | |
| 53 | + pool.borrowConnection(100, MILLISECONDS); | |
| 54 | + } catch (TimeoutException e) { | |
| 55 | + timedOut = true; | |
| 56 | + } | |
| 57 | + assertThat(timedOut).isTrue(); | |
| 58 | + } | |
| 28 | 59 | |
| 29 | 60 | /** |
| 30 | - * Test for #JAVA-349 - Negative openConnection count results in broken connection release. | |
| 31 | - * <p/> | |
| 61 | + * Ensures that if a variable-sized pool has filled up to its maximum connections that borrowConnection will | |
| 62 | + * timeout instead of creating a new connection. | |
| 63 | + * | |
| 64 | + * @since 2.0.10, 2.1.6 | |
| 65 | + * @jira_ticket JAVA-419 | |
| 66 | + * @test_category connection:connection_pool | |
| 67 | + */ | |
| 68 | + @Test(groups = "short") | |
| 69 | + public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws ConnectionException, TimeoutException { | |
| 70 | + HostConnectionPool pool = createPool(1, 2); | |
| 71 | + | |
| 72 | + assertThat(pool.connections.size()).isEqualTo(1); | |
| 73 | + List<PooledConnection> coreConnections = Lists.newArrayList(pool.connections); | |
| 74 | + | |
| 75 | + // | |
| 76 | + for (int i = 0; i < 128; i++) { | |
| 77 | + PooledConnection connection = pool.borrowConnection(100, MILLISECONDS); | |
| 78 | + assertThat(coreConnections).contains(connection); | |
| 79 | + } | |
| 80 | + | |
| 81 | + // Borrow more and ensure the connection returned is a non-core connection. | |
| 82 | + for (int i = 0; i < 128; i++) { | |
| 83 | + PooledConnection connection = pool.borrowConnection(100, MILLISECONDS); | |
| 84 | + assertThat(coreConnections).doesNotContain(connection); | |
| 85 | + } | |
| 86 | + | |
| 87 | + boolean timedOut = false; | |
| 88 | + try { | |
| 89 | + pool.borrowConnection(100, MILLISECONDS); | |
| 90 | + } catch (TimeoutException e) { | |
| 91 | + timedOut = true; | |
| 92 | + } | |
| 93 | + assertThat(timedOut).isTrue(); | |
| 94 | + } | |
| 95 | + | |
| 96 | + /** | |
| 97 | + * Ensures that if the core connection pool is full that borrowConnection will create and use a new connection. | |
| 98 | + * | |
| 99 | + * @since 2.0.10, 2.1.6 | |
| 100 | + * @jira_ticket JAVA-419 | |
| 101 | + * @test_category connection:connection_pool | |
| 102 | + */ | |
| 103 | + @Test(groups = "short") | |
| 104 | + public void should_add_extra_connection_when_core_full() throws ConnectionException, TimeoutException, InterruptedException { | |
| 105 | + cluster.getConfiguration().getPoolingOptions() | |
| 106 | + .setIdleTimeoutSeconds(20); | |
| 107 | + | |
| 108 | + HostConnectionPool pool = createPool(1, 2); | |
| 109 | + PooledConnection core = pool.connections.get(0); | |
| 110 | + | |
| 111 | + // Fill core connection | |
| 112 | + for (int i = 0; i < 128; i++) | |
| 113 | + assertThat( | |
| 114 | + pool.borrowConnection(100, MILLISECONDS) | |
| 115 | + ).isEqualTo(core); | |
| 116 | + | |
| 117 | + // Reaching 128 on the core connection should have triggered the creation of an extra one | |
| 118 | + TimeUnit.MILLISECONDS.sleep(100); | |
| 119 | + assertThat(pool.connections).hasSize(2); | |
| 120 | + } | |
| 121 | + | |
| 122 | + /** | |
| 123 | + * Ensures that a trashed connection that has not been timed out should be resurrected into the connection pool if | |
| 124 | + * borrowConnection is called and a new connection is needed. | |
| 125 | + * | |
| 126 | + * @since 2.0.10, 2.1.6 | |
| 127 | + * @jira_ticket JAVA-419 | |
| 128 | + * @test_category connection:connection_pool | |
| 129 | + */ | |
| 130 | + @Test(groups = "long") | |
| 131 | + public void should_resurrect_trashed_connection_within_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException { | |
| 132 | + cluster.getConfiguration().getPoolingOptions() | |
| 133 | + .setIdleTimeoutSeconds(20); | |
| 134 | + | |
| 135 | + HostConnectionPool pool = createPool(1, 2); | |
| 136 | + PooledConnection connection1 = pool.connections.get(0); | |
| 137 | + | |
| 138 | + for (int i = 0; i < 101; i++) | |
| 139 | + assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1); | |
| 140 | + | |
| 141 | + TimeUnit.MILLISECONDS.sleep(100); | |
| 142 | + assertThat(pool.connections).hasSize(2); | |
| 143 | + PooledConnection connection2 = pool.connections.get(1); | |
| 144 | + | |
| 145 | + assertThat(connection1.inFlight.get()).isEqualTo(101); | |
| 146 | + assertThat(connection2.inFlight.get()).isEqualTo(0); | |
| 147 | + | |
| 148 | + // Go back under the capacity of 1 connection | |
| 149 | + for (int i = 0; i < 51; i++) | |
| 150 | + pool.returnConnection(connection1); | |
| 151 | + | |
| 152 | + assertThat(connection1.inFlight.get()).isEqualTo(50); | |
| 153 | + assertThat(connection2.inFlight.get()).isEqualTo(0); | |
| 154 | + | |
| 155 | + // Given enough time, one connection gets trashed (and the implementation picks the first one) | |
| 156 | + TimeUnit.SECONDS.sleep(20); | |
| 157 | + assertThat(pool.connections).containsExactly(connection2); | |
| 158 | + assertThat(pool.trash).containsExactly(connection1); | |
| 159 | + | |
| 160 | + // Now borrow enough to go just under the 1 connection threshold | |
| 161 | + for (int i = 0; i < 50; i++) | |
| 162 | + pool.borrowConnection(100, MILLISECONDS); | |
| 163 | + | |
| 164 | + assertThat(pool.connections).containsExactly(connection2); | |
| 165 | + assertThat(pool.trash).containsExactly(connection1); | |
| 166 | + assertThat(connection1.inFlight.get()).isEqualTo(50); | |
| 167 | + assertThat(connection2.inFlight.get()).isEqualTo(50); | |
| 168 | + | |
| 169 | + // Borrowing one more time should resurrect the trashed connection | |
| 170 | + pool.borrowConnection(100, MILLISECONDS); | |
| 171 | + TimeUnit.MILLISECONDS.sleep(100); | |
| 172 | + | |
| 173 | + assertThat(pool.connections).containsExactly(connection2, connection1); | |
| 174 | + assertThat(pool.trash).isEmpty(); | |
| 175 | + assertThat(connection1.inFlight.get()).isEqualTo(50); | |
| 176 | + assertThat(connection2.inFlight.get()).isEqualTo(51); | |
| 177 | + } | |
| 178 | + | |
| 179 | + /** | |
| 180 | + * Ensures that a trashed connection that has been timed out should not be resurrected into the connection pool if | |
| 181 | + * borrowConnection is called and a new connection is needed. | |
| 182 | + * | |
| 183 | + * @since 2.0.10, 2.1.6 | |
| 184 | + * @jira_ticket JAVA-419 | |
| 185 | + * @test_category connection:connection_pool | |
| 186 | + */ | |
| 187 | + @Test(groups = "long") | |
| 188 | + public void should_not_resurrect_trashed_connection_after_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException { | |
| 189 | + cluster.getConfiguration().getPoolingOptions() | |
| 190 | + .setIdleTimeoutSeconds(20); | |
| 191 | + | |
| 192 | + HostConnectionPool pool = createPool(1, 2); | |
| 193 | + PooledConnection connection1 = pool.connections.get(0); | |
| 194 | + | |
| 195 | + for (int i = 0; i < 101; i++) | |
| 196 | + assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1); | |
| 197 | + | |
| 198 | + TimeUnit.MILLISECONDS.sleep(100); | |
| 199 | + assertThat(pool.connections).hasSize(2); | |
| 200 | + PooledConnection connection2 = pool.connections.get(1); | |
| 201 | + | |
| 202 | + assertThat(connection1.inFlight.get()).isEqualTo(101); | |
| 203 | + assertThat(connection2.inFlight.get()).isEqualTo(0); | |
| 204 | + | |
| 205 | + // Go back under the capacity of 1 connection | |
| 206 | + for (int i = 0; i < 51; i++) | |
| 207 | + pool.returnConnection(connection1); | |
| 208 | + | |
| 209 | + assertThat(connection1.inFlight.get()).isEqualTo(50); | |
| 210 | + assertThat(connection2.inFlight.get()).isEqualTo(0); | |
| 211 | + | |
| 212 | + // Given enough time, one connection gets trashed (and the implementation picks the first one) | |
| 213 | + TimeUnit.SECONDS.sleep(20); | |
| 214 | + assertThat(pool.connections).containsExactly(connection2); | |
| 215 | + assertThat(pool.trash).containsExactly(connection1); | |
| 216 | + | |
| 217 | + // Return trashed connection down to 0 inFlight | |
| 218 | + for (int i = 0; i < 50; i++) | |
| 219 | + pool.returnConnection(connection1); | |
| 220 | + assertThat(connection1.inFlight.get()).isEqualTo(0); | |
| 221 | + | |
| 222 | + // Give enough time for trashed connection to be cleaned up from the trash: | |
| 223 | + TimeUnit.SECONDS.sleep(30); | |
| 224 | + assertThat(pool.connections).containsExactly(connection2); | |
| 225 | + assertThat(pool.trash).isEmpty(); | |
| 226 | + assertThat(connection1.isClosed()).isTrue(); | |
| 227 | + | |
| 228 | + // Fill the live connection to go over the threshold where a second one is needed | |
| 229 | + for (int i = 0; i < 101; i++) | |
| 230 | + assertThat(pool.borrowConnection(100, TimeUnit.MILLISECONDS)).isEqualTo(connection2); | |
| 231 | + assertThat(connection2.inFlight.get()).isEqualTo(101); | |
| 232 | + TimeUnit.MILLISECONDS.sleep(100); | |
| 233 | + | |
| 234 | + // Borrow again to get the new connection | |
| 235 | + PooledConnection connection3 = pool.borrowConnection(100, MILLISECONDS); | |
| 236 | + assertThat(connection3) | |
| 237 | + .isNotEqualTo(connection2) // should not be the full connection | |
| 238 | + .isNotEqualTo(connection1); // should not be the previously trashed one | |
| 239 | + } | |
| 240 | + | |
| 241 | + /** | |
| 242 | + * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests. | |
| 243 | + * | |
| 244 | + * @since 2.0.10, 2.1.6 | |
| 245 | + * @jira_ticket JAVA-419 | |
| 246 | + * @test_category connection:connection_pool | |
| 247 | + */ | |
| 248 | + @Test(groups = "long") | |
| 249 | + public void should_not_close_trashed_connection_until_no_in_flight() | |
| 250 | + throws ConnectionException, TimeoutException, InterruptedException { | |
| 251 | + cluster.getConfiguration().getPoolingOptions() | |
| 252 | + .setIdleTimeoutSeconds(20); | |
| 253 | + | |
| 254 | + HostConnectionPool pool = createPool(1, 2); | |
| 255 | + PooledConnection connection1 = pool.connections.get(0); | |
| 256 | + | |
| 257 | + // Fill core connection enough to trigger creation of another one | |
| 258 | + for (int i = 0; i < 110; i++) | |
| 259 | + assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1); | |
| 260 | + | |
| 261 | + TimeUnit.MILLISECONDS.sleep(100); | |
| 262 | + assertThat(pool.connections).hasSize(2); | |
| 263 | + | |
| 264 | + // Return enough times to get back under the threshold where one connection is enough | |
| 265 | + for (int i = 0; i < 50; i++) | |
| 266 | + pool.returnConnection(connection1); | |
| 267 | + | |
| 268 | + // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one. | |
| 269 | + // It still has in-flight requests so should not get closed. | |
| 270 | + TimeUnit.SECONDS.sleep(30); | |
| 271 | + assertThat(pool.trash).containsExactly(connection1); | |
| 272 | + assertThat(connection1.inFlight.get()).isEqualTo(60); | |
| 273 | + assertThat(connection1.isClosed()).isFalse(); | |
| 274 | + | |
| 275 | + // Consume all inFlight requests on the trashed connection. | |
| 276 | + while (connection1.inFlight.get() > 0) { | |
| 277 | + pool.returnConnection(connection1); | |
| 278 | + } | |
| 279 | + | |
| 280 | + // Sleep enough time for the connection to be consider idled and closed. | |
| 281 | + TimeUnit.SECONDS.sleep(30); | |
| 282 | + | |
| 283 | + // The connection should be now closed. | |
| 284 | + // The trashed connection should be closed and not in the pool or trash. | |
| 285 | + assertThat(connection1.isClosed()).isTrue(); | |
| 286 | + assertThat(pool.connections).doesNotContain(connection1); | |
| 287 | + assertThat(pool.trash).doesNotContain(connection1); | |
| 288 | + } | |
| 289 | + | |
| 290 | + /** | |
| 291 | + * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that | |
| 292 | + * the connection is put in the trash. | |
| 293 | + * | |
| 294 | + * @since 2.0.10, 2.1.6 | |
| 295 | + * @jira_ticket JAVA-419 | |
| 296 | + * @test_category connection:connection_pool | |
| 297 | + */ | |
| 298 | + @Test(groups = "short") | |
| 299 | + public void should_trash_on_returning_connection_with_insufficient_streams() | |
| 300 | + throws ConnectionException, TimeoutException, InterruptedException { | |
| 301 | + HostConnectionPool pool = createPool(1, 2); | |
| 302 | + PooledConnection core = pool.connections.get(0); | |
| 303 | + | |
| 304 | + for (int i = 0; i < 128; i++) | |
| 305 | + assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core); | |
| 306 | + | |
| 307 | + TimeUnit.MILLISECONDS.sleep(100); | |
| 308 | + assertThat(pool.connections).hasSize(2); | |
| 309 | + | |
| 310 | + // Grab the new non-core connection and replace it with a spy. | |
| 311 | + PooledConnection extra1 = spy(pool.connections.get(1)); | |
| 312 | + pool.connections.set(1, extra1); | |
| 313 | + | |
| 314 | + // Borrow 10 times to ensure pool is utilized. | |
| 315 | + for (int i = 0; i < 10; i++) { | |
| 316 | + assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(extra1); | |
| 317 | + } | |
| 318 | + | |
| 319 | + // Return connection, it should not be trashed since it still has 9 inflight requests. | |
| 320 | + pool.returnConnection(extra1); | |
| 321 | + assertThat(pool.connections).hasSize(2); | |
| 322 | + | |
| 323 | + // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams. | |
| 324 | + // this should cause the connection to be replaced and trashed on returnConnection. | |
| 325 | + doReturn(0).when(extra1).maxAvailableStreams(); | |
| 326 | + | |
| 327 | + // On returning of the connection, should detect that there are no available streams and trash it. | |
| 328 | + pool.returnConnection(extra1); | |
| 329 | + assertThat(pool.connections).hasSize(1); | |
| 330 | + } | |
| 331 | + | |
| 332 | + private HostConnectionPool createPool(int coreConnections, int maxConnections) { | |
| 333 | + cluster.getConfiguration().getPoolingOptions() | |
| 334 | + .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections) | |
| 335 | + .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections); | |
| 336 | + Session session = cluster.connect(); | |
| 337 | + Host host = TestUtils.findHost(cluster, 1); | |
| 338 | + return ((SessionManager)session).pools.get(host); | |
| 339 | + } | |
| 340 | + | |
| 341 | + /** | |
| 342 | + * <p> | |
| 32 | 343 | * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the |
| 33 | 344 | * insertions are being executed, the number of opened connection is monitored. |
| 34 | 345 | * <p/> |
| 35 | 346 | * If at anytime, the number of opened connections is negative, this test will fail. |
| 36 | 347 | * |
| 37 | - * @throws InterruptedException | |
| 348 | + * @since 2.0.6, 2.1.1 | |
| 349 | + * @jira_ticket JAVA-349 | |
| 350 | + * @test_category connection:connection_pool | |
| 38 | 351 | */ |
| 39 | 352 | @Test(groups = "long", enabled = false /* this test causes timeouts on Jenkins */) |
| 40 | 353 | public void open_connections_metric_should_always_be_positive() throws InterruptedException { |