Elffuss BraidHub

kikocis/java-driver public

Merge pull request #262 from datastax/java419

Reintroduce pool idle timeout (JAVA-419)
Changesetfa3b8ab03aa1a3e66fb6f124fd766f0bb9dd50e788d111f5ad6cf474a97fb2f3
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-03-27 19:17 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-03-27 19:17 +01:00
Parents42972cf86120, 2964aed846e2

Browse the files at this changeset

9 files changed

modified driver-core/CHANGELOG.rst +2 −0
@@ -20,6 +20,8 @@
2020 - [improvement] Expose TokenRange#contains (JAVA-687)
2121 - [new feature] Expose values of BoundStatement (JAVA-547)
2222 - [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)
2325
2426 Merged from 2.0.9_fixes branch:
2527
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +15 −0
@@ -1168,6 +1168,8 @@
11681168
11691169 this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this);
11701170 this.listeners = new CopyOnWriteArraySet<Host.StateListener>(listeners);
1171+
1172+ this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS);
11711173 }
11721174
11731175 // Initialization is not too performance intensive and in practice there shouldn't be contention
@@ -2226,6 +2228,19 @@
22262228 }).start();
22272229 }
22282230 }
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+ }
22292244 }
22302245
22312246 /**
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +161 −50
@@ -36,6 +36,8 @@
3636
3737 import com.datastax.driver.core.exceptions.AuthenticationException;
3838
39+import static com.datastax.driver.core.PooledConnection.State.*;
40+
3941 class HostConnectionPool {
4042
4143 private static final Logger logger = LoggerFactory.getLogger(HostConnectionPool.class);
@@ -53,7 +55,11 @@
5355
5456 final List<PooledConnection> connections;
5557 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>();
5763
5864 private volatile int waiter = 0;
5965 private final Lock waitLock = new ReentrantLock(true);
@@ -63,6 +69,7 @@
6369
6470 private final AtomicInteger scheduledForCreation = new AtomicInteger();
6571
72+ private volatile boolean isClosing;
6673 private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
6774
6875 public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
@@ -132,6 +139,7 @@
132139 manager.blockingExecutor().submit(newConnectionTask);
133140 }
134141 PooledConnection c = waitForConnection(timeout, unit);
142+ totalInFlight.incrementAndGet();
135143 c.setKeyspace(manager.poolsState.keyspace);
136144 return c;
137145 }
@@ -146,9 +154,6 @@
146154 }
147155 }
148156
149- if (minInFlight >= options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance) && connections.size() < options().getMaxConnectionsPerHost(hostDistance))
150- maybeSpawnNewConnection();
151-
152157 if (leastBusy == null) {
153158 // We could have raced with a shutdown since the last check
154159 if (isClosed())
@@ -170,6 +175,24 @@
170175 break;
171176 }
172177 }
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+
173196 leastBusy.setKeyspace(manager.poolsState.keyspace);
174197 return leastBusy;
175198 }
@@ -260,7 +283,8 @@
260283 }
261284
262285 public void returnConnection(PooledConnection connection) {
263- int inFlight = connection.inFlight.decrementAndGet();
286+ connection.inFlight.decrementAndGet();
287+ totalInFlight.decrementAndGet();
264288
265289 if (isClosed()) {
266290 close(connection);
@@ -273,13 +297,8 @@
273297 return;
274298 }
275299
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) {
283302 replaceConnection(connection);
284303 } else {
285304 signalAvailableConnection();
@@ -290,44 +309,38 @@
290309 // Trash the connection and create a new one, but we don't call trashConnection
291310 // directly because we want to make sure the connection is always trashed.
292311 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();
295315 maybeSpawnNewConnection();
316+ connection.maxIdleTime = Long.MIN_VALUE;
296317 doTrashConnection(connection);
297318 }
298319
299320 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;
308323
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;
311330 }
312331
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);
322338 return true;
323339 }
324340
325341 private void doTrashConnection(PooledConnection connection) {
326- trash.add(connection);
327342 connections.remove(connection);
328-
329- if (connection.inFlight.get() == 0 && trash.remove(connection))
330- close(connection);
343+ trash.add(connection);
331344 }
332345
333346 private boolean addConnectionIfUnderMaximum() {
@@ -342,14 +355,29 @@
342355 break;
343356 }
344357
345- if (isClosed()) {
358+ if (isClosing) {
346359 open.decrementAndGet();
347360 return false;
348361 }
349362
350363 // Now really open the connection
351364 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+
353381 signalAvailableConnection();
354382 return true;
355383 } catch (InterruptedException e) {
@@ -378,6 +406,27 @@
378406 }
379407 }
380408
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+
381430 private void maybeSpawnNewConnection() {
382431 while (true) {
383432 int inCreation = scheduledForCreation.get();
@@ -387,21 +436,71 @@
387436 break;
388437 }
389438
390- logger.debug("Creating new connection on busy pool to {}", host);
391439 manager.blockingExecutor().submit(newConnectionTask);
392440 }
393441
394442 void replaceDefunctConnection(final PooledConnection connection) {
395- if (connection.markForTrash.compareAndSet(false, true))
443+ if (connection.state.compareAndSet(OPEN, GONE))
396444 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+ });
398452 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+ }
403502 }
404- });
503+ }
405504 }
406505
407506 private void close(final Connection connection) {
@@ -418,7 +517,9 @@
418517 if (future != null)
419518 return future;
420519
421- // Wake up all threads that waits
520+ isClosing = true;
521+
522+ // Wake up all threads that wait
422523 signalAllAvailableConnection();
423524
424525 future = new CloseFuture.Forwarding(discardAvailableConnections());
@@ -432,22 +533,32 @@
432533 return open.get();
433534 }
434535
536+ public int trashed() {
537+ return trash.size();
538+ }
539+
435540 private List<CloseFuture> discardAvailableConnections() {
436541 // This can happen if creating the connections in the constructor fails
437542 if (connections == null)
438543 return Lists.newArrayList(CloseFuture.immediateFuture());
439544
440- List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size());
545+ List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size());
546+
441547 for (final PooledConnection connection : connections) {
442548 CloseFuture future = connection.closeAsync();
443549 future.addListener(new Runnable() {
444550 public void run() {
445- if (connection.markForTrash.compareAndSet(false, true))
551+ if (connection.state.compareAndSet(OPEN, GONE))
446552 open.decrementAndGet();
447553 }
448554 }, MoreExecutors.sameThreadExecutor());
449555 futures.add(future);
450556 }
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+
451562 return futures;
452563 }
453564
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +24 −0
@@ -69,6 +69,16 @@
6969 return value;
7070 }
7171 });
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+ });
7282
7383 private final Gauge<Integer> executorQueueDepth = registry.register("executor-queue-depth", new Gauge<Integer>() {
7484 @Override
@@ -205,6 +215,20 @@
205215 return openConnections;
206216 }
207217
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+
208232 /**
209233 * @return The number of queued up tasks in the non-blocking executor (Cassandra Java Driver workers).
210234 */
modified driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +6 −3
@@ -16,7 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import java.net.InetSocketAddress;
19-import java.util.concurrent.atomic.AtomicBoolean;
19+import java.util.concurrent.atomic.AtomicReference;
2020
2121 /**
2222 * A connection that is associated to a pool.
@@ -25,8 +25,11 @@
2525
2626 final HostConnectionPool pool;
2727
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;
3033
3134 PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
3235 super(name, address, factory);
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +39 −36
@@ -31,43 +31,36 @@
3131 * more connections are created up to the configurable maximum number of
3232 * connections ({@link #getMaxConnectionsPerHost}). When the pool exceeds
3333 * 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.
3635 * <p>
3736 * Each of these parameters can be separately set for {@code LOCAL} and
3837 * {@code REMOTE} hosts ({@link HostDistance}). For {@code IGNORED} hosts,
3938 * 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).
4639 */
4740 public class PoolingOptions {
4841
4942 // Note: we could use an enumMap or similar, but synchronization would
5043 // be more costly so let's stick to volatile in for now.
51- private static final int DEFAULT_MIN_REQUESTS = 25;
5244 private static final int DEFAULT_MAX_REQUESTS = 100;
5345
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;
5648
5749 private static final int DEFAULT_MAX_POOL_LOCAL = 8;
5850 private static final int DEFAULT_MAX_POOL_REMOTE = 2;
5951
52+ private static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120;
6053 private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
6154 private static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30;
6255
6356 private volatile Cluster.Manager manager;
6457
65- private final int[] minSimultaneousRequests = new int[]{ DEFAULT_MIN_REQUESTS, DEFAULT_MIN_REQUESTS, 0 };
6658 private final int[] maxSimultaneousRequests = new int[]{ DEFAULT_MAX_REQUESTS, DEFAULT_MAX_REQUESTS, 0 };
6759
6860 private final int[] coreConnections = new int[] { DEFAULT_CORE_POOL_LOCAL, DEFAULT_CORE_POOL_REMOTE, 0 };
6961 private final int[] maxConnections = new int[] { DEFAULT_MAX_POOL_LOCAL , DEFAULT_MAX_POOL_REMOTE, 0 };
7062
63+ private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
7164 private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
7265 private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
7366
@@ -91,9 +84,12 @@
9184 *
9285 * @param distance the {@code HostDistance} for which to return this threshold.
9386 * @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.
9489 */
90+ @Deprecated
9591 public int getMinSimultaneousRequestsPerConnectionThreshold(HostDistance distance) {
96- return minSimultaneousRequests[distance.ordinal()];
92+ return 0;
9793 }
9894
9995 /**
@@ -106,14 +102,11 @@
106102 *
107103 * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED}, or if {@code minSimultaneousRequests}
108104 * 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.
109107 */
108+ @Deprecated
110109 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;
117110 return this;
118111 }
119112
@@ -156,7 +149,6 @@
156149 throw new IllegalArgumentException("Cannot set max simultaneous requests per connection threshold for " + distance + " hosts");
157150
158151 checkRequestsPerConnectionRange(newMaxSimultaneousRequests, "Max simultaneous requests per connection", distance);
159- checkRequestsPerConnectionOrder(minSimultaneousRequests[distance.ordinal()], newMaxSimultaneousRequests, distance);
160152 maxSimultaneousRequests[distance.ordinal()] = newMaxSimultaneousRequests;
161153 return this;
162154 }
@@ -177,11 +169,6 @@
177169
178170 /**
179171 * 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).
185172 *
186173 * @param distance the {@code HostDistance} for which to set this threshold.
187174 * @param newCoreConnections the value to set
@@ -217,11 +204,6 @@
217204
218205 /**
219206 * 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).
225207 *
226208 * @param distance the {@code HostDistance} for which to set this threshold.
227209 * @param newMaxConnections the value to set
@@ -239,6 +221,33 @@
239221 return this;
240222 }
241223
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+
242251 /**
243252 * Returns the timeout when trying to acquire a connection from a host's pool.
244253 *
@@ -326,12 +335,6 @@
326335 StreamIdGenerator.MAX_STREAM_PER_CONNECTION));
327336 }
328337
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-
335338 private static void checkConnectionsPerHostOrder(int core, int max, HostDistance distance) {
336339 if (core > max)
337340 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 @@
1717
1818 import java.io.Closeable;
1919 import java.util.Collection;
20-import java.util.Map;
2120
2221 import com.google.common.util.concurrent.ListenableFuture;
2322
@@ -376,6 +375,9 @@
376375
377376 /**
378377 * 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)}.
379381 *
380382 * @param host the host to get open connections for.
381383 * @return The number of open connections to {@code host}. If the session
@@ -383,6 +385,20 @@
383385 */
384386 public int getOpenConnections(Host host);
385387
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+
386402 /**
387403 * The number of queries that are currently being executed though a given host.
388404 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +16 −3
@@ -556,11 +556,18 @@
556556 return future;
557557 }
558558
559+ void cleanupIdleConnections(long now) {
560+ for (HostConnectionPool pool : pools.values()) {
561+ pool.cleanupIdleConnections(now);
562+ }
563+ }
564+
559565 private static class State implements Session.State {
560566
561567 private final SessionManager session;
562568 private final List<Host> connectedHosts;
563569 private final int[] openConnections;
570+ private final int[] trashedConnections;
564571 private final int[] inFlightQueries;
565572
566573 private State(SessionManager session) {
@@ -568,6 +575,7 @@
568575 this.connectedHosts = ImmutableList.copyOf(session.pools.keySet());
569576
570577 this.openConnections = new int[connectedHosts.size()];
578+ this.trashedConnections = new int[connectedHosts.size()];
571579 this.inFlightQueries = new int[connectedHosts.size()];
572580
573581 int i = 0;
@@ -578,14 +586,14 @@
578586 // connections will be slightly weird, but it's unlikely enough that we don't bother avoiding.
579587 if (p == null) {
580588 openConnections[i] = 0;
589+ trashedConnections[i] = 0;
581590 inFlightQueries[i] = 0;
582591 continue;
583592 }
584593
585594 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();
589597 i++;
590598 }
591599 }
@@ -616,6 +624,11 @@
616624 return i < 0 ? 0 : openConnections[i];
617625 }
618626
627+ public int getTrashedConnections(Host host) {
628+ int i = getIdx(host);
629+ return i < 0 ? 0 : trashedConnections[i];
630+ }
631+
619632 public int getInFlightQueries(Host host) {
620633 int i = getIdx(host);
621634 return i < 0 ? 0 : inFlightQueries[i];
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +324 −11
@@ -1,17 +1,20 @@
11 package com.datastax.driver.core;
22
3-import com.codahale.metrics.Gauge;
4-import com.google.common.collect.Lists;
5-import org.testng.annotations.Test;
6-
73 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.*;
126 import java.util.concurrent.atomic.AtomicBoolean;
137
8+import static java.util.concurrent.TimeUnit.MILLISECONDS;
149 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;
1518 import static org.testng.Assert.fail;
1619
1720 public class HostConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -25,16 +28,326 @@
2528 return Lists.newArrayList(sb.toString());
2629 }
2730
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+ }
2859
2960 /**
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>
32343 * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the
33344 * insertions are being executed, the number of opened connection is monitored.
34345 * <p/>
35346 * If at anytime, the number of opened connections is negative, this test will fail.
36347 *
37- * @throws InterruptedException
348+ * @since 2.0.6, 2.1.1
349+ * @jira_ticket JAVA-349
350+ * @test_category connection:connection_pool
38351 */
39352 @Test(groups = "long", enabled = false /* this test causes timeouts on Jenkins */)
40353 public void open_connections_metric_should_always_be_positive() throws InterruptedException {