kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | d0af041c292a48a921f57e7221d0c603279b750c298d7917c5ef1e6a7539cff9 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2014-12-30 12:20 +01:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-03-27 19:11 +01:00 |
| Parents | 42972cf86120 |
7 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 +157 −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 | + private 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; | |
| 403 | 485 | } |
| 404 | - }); | |
| 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 | + } | |
| 502 | + } | |
| 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()); |
| @@ -437,17 +538,23 @@ | ||
| 437 | 538 | if (connections == null) |
| 438 | 539 | return Lists.newArrayList(CloseFuture.immediateFuture()); |
| 439 | 540 | |
| 440 | - List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size()); | |
| 541 | + List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size()); | |
| 542 | + | |
| 441 | 543 | for (final PooledConnection connection : connections) { |
| 442 | 544 | CloseFuture future = connection.closeAsync(); |
| 443 | 545 | future.addListener(new Runnable() { |
| 444 | 546 | public void run() { |
| 445 | - if (connection.markForTrash.compareAndSet(false, true)) | |
| 547 | + if (connection.state.compareAndSet(OPEN, GONE)) | |
| 446 | 548 | open.decrementAndGet(); |
| 447 | 549 | } |
| 448 | 550 | }, MoreExecutors.sameThreadExecutor()); |
| 449 | 551 | futures.add(future); |
| 450 | 552 | } |
| 553 | + | |
| 554 | + // Some connections in the trash might still be open if they hadn't reached their idle timeout | |
| 555 | + for (PooledConnection connection : trash) | |
| 556 | + futures.add(connection.closeAsync()); | |
| 557 | + | |
| 451 | 558 | return futures; |
| 452 | 559 | } |
| 453 | 560 |
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/SessionManager.java +6 −0
| @@ -556,6 +556,12 @@ | ||
| 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; |
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +133 −8
| @@ -1,17 +1,18 @@ | ||
| 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; | |
| 15 | 16 | import static org.testng.Assert.fail; |
| 16 | 17 | |
| 17 | 18 | public class HostConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster { |
| @@ -25,6 +26,130 @@ | ||
| 25 | 26 | return Lists.newArrayList(sb.toString()); |
| 26 | 27 | } |
| 27 | 28 | |
| 29 | + @Test(groups = "short") | |
| 30 | + public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException { | |
| 31 | + HostConnectionPool pool = createPool(2, 2); | |
| 32 | + | |
| 33 | + assertThat(pool.connections.size()).isEqualTo(2); | |
| 34 | + List<PooledConnection> coreConnections = Lists.newArrayList(pool.connections); | |
| 35 | + | |
| 36 | + for (int i = 0; i < 256; i++) { | |
| 37 | + PooledConnection connection = pool.borrowConnection(100, MILLISECONDS); | |
| 38 | + assertThat(coreConnections).contains(connection); | |
| 39 | + } | |
| 40 | + | |
| 41 | + boolean timedOut = false; | |
| 42 | + try { | |
| 43 | + pool.borrowConnection(100, MILLISECONDS); | |
| 44 | + } catch (TimeoutException e) { | |
| 45 | + timedOut = true; | |
| 46 | + } | |
| 47 | + assertThat(timedOut).isTrue(); | |
| 48 | + } | |
| 49 | + | |
| 50 | + @Test(groups = "short") | |
| 51 | + public void should_add_extra_connection_when_core_full() throws ConnectionException, TimeoutException, InterruptedException { | |
| 52 | + cluster.getConfiguration().getPoolingOptions() | |
| 53 | + .setIdleTimeoutSeconds(20) | |
| 54 | + .setMinSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, 1) | |
| 55 | + .setMaxConnectionsPerHost(HostDistance.LOCAL, 128); | |
| 56 | + | |
| 57 | + HostConnectionPool pool = createPool(1, 2); | |
| 58 | + PooledConnection core = pool.connections.get(0); | |
| 59 | + | |
| 60 | + // Fill core connection | |
| 61 | + for (int i = 0; i < 128; i++) | |
| 62 | + assertThat( | |
| 63 | + pool.borrowConnection(100, MILLISECONDS) | |
| 64 | + ).isEqualTo(core); | |
| 65 | + | |
| 66 | + // Reaching 128 on the core connection should have triggered the creation of an extra one | |
| 67 | + TimeUnit.MILLISECONDS.sleep(100); | |
| 68 | + assertThat(pool.connections).hasSize(2); | |
| 69 | + PooledConnection extra1 = pool.connections.get(1); | |
| 70 | + | |
| 71 | + assertThat( | |
| 72 | + pool.borrowConnection(100, MILLISECONDS) | |
| 73 | + ).isEqualTo(extra1); | |
| 74 | + | |
| 75 | + // If the extra connection is returned it gets trashed | |
| 76 | + pool.returnConnection(extra1); | |
| 77 | + assertThat(pool.connections).hasSize(1); | |
| 78 | + | |
| 79 | + // If the core connection gets returned we can borrow it again | |
| 80 | + pool.returnConnection(core); | |
| 81 | + assertThat( | |
| 82 | + pool.borrowConnection(100, MILLISECONDS) | |
| 83 | + ).isEqualTo(core); | |
| 84 | + } | |
| 85 | + | |
| 86 | + @Test(groups = "short") | |
| 87 | + public void should_resurrect_trashed_connection_within_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException { | |
| 88 | + cluster.getConfiguration().getPoolingOptions() | |
| 89 | + .setIdleTimeoutSeconds(20) | |
| 90 | + .setMinSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, 1) | |
| 91 | + .setMaxConnectionsPerHost(HostDistance.LOCAL, 128); | |
| 92 | + | |
| 93 | + HostConnectionPool pool = createPool(1, 2); | |
| 94 | + PooledConnection core = pool.connections.get(0); | |
| 95 | + | |
| 96 | + for (int i = 0; i < 128; i++) | |
| 97 | + assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core); | |
| 98 | + | |
| 99 | + TimeUnit.MILLISECONDS.sleep(100); | |
| 100 | + assertThat(pool.connections).hasSize(2); | |
| 101 | + PooledConnection extra1 = pool.connections.get(1); | |
| 102 | + | |
| 103 | + assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(extra1); | |
| 104 | + pool.returnConnection(extra1); | |
| 105 | + assertThat(pool.connections).hasSize(1); | |
| 106 | + | |
| 107 | + // extra1 is now in the trash, core still full | |
| 108 | + // Borrowing again should resurrect extra1 from the trash | |
| 109 | + assertThat( | |
| 110 | + pool.borrowConnection(100, MILLISECONDS) | |
| 111 | + ).isEqualTo(extra1); | |
| 112 | + assertThat(pool.connections).hasSize(2); | |
| 113 | + } | |
| 114 | + | |
| 115 | + @Test(groups = "long") | |
| 116 | + public void should_not_resurrect_trashed_connection_after_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException { | |
| 117 | + cluster.getConfiguration().getPoolingOptions() | |
| 118 | + .setIdleTimeoutSeconds(20) | |
| 119 | + .setMinSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, 1) | |
| 120 | + .setMaxConnectionsPerHost(HostDistance.LOCAL, 128); | |
| 121 | + | |
| 122 | + HostConnectionPool pool = createPool(1, 2); | |
| 123 | + PooledConnection core = pool.connections.get(0); | |
| 124 | + | |
| 125 | + for (int i = 0; i < 128; i++) | |
| 126 | + assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core); | |
| 127 | + | |
| 128 | + TimeUnit.MILLISECONDS.sleep(100); | |
| 129 | + assertThat(pool.connections).hasSize(2); | |
| 130 | + PooledConnection extra1 = pool.connections.get(1); | |
| 131 | + | |
| 132 | + assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(extra1); | |
| 133 | + pool.returnConnection(extra1); | |
| 134 | + assertThat(pool.connections).hasSize(1); | |
| 135 | + | |
| 136 | + // Give enough time for extra1 to be cleaned up from the trash: | |
| 137 | + TimeUnit.SECONDS.sleep(30); | |
| 138 | + | |
| 139 | + // Next borrow should create another connection | |
| 140 | + PooledConnection extra2 = pool.borrowConnection(100, MILLISECONDS); | |
| 141 | + assertThat(extra2).isNotEqualTo(extra1); | |
| 142 | + assertThat(extra1.isClosed()).isTrue(); | |
| 143 | + } | |
| 144 | + | |
| 145 | + private HostConnectionPool createPool(int coreConnections, int maxConnections) { | |
| 146 | + cluster.getConfiguration().getPoolingOptions() | |
| 147 | + .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections) | |
| 148 | + .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections); | |
| 149 | + Session session = cluster.connect(); | |
| 150 | + Host host = TestUtils.findHost(cluster, 1); | |
| 151 | + return ((SessionManager)session).pools.get(host); | |
| 152 | + } | |
| 28 | 153 | |
| 29 | 154 | /** |
| 30 | 155 | * Test for #JAVA-349 - Negative openConnection count results in broken connection release. |