kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 1921aa68332c1f9d852985e5656c97dfabb13684b582a9331d6ae0a287c84fe6 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2014-10-21 10:26 +02:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2014-10-22 11:53 +02:00 |
| Parents | a6261f6ac1b1 |
7 files changed
modified driver-core/CHANGELOG.rst +1 −0
| @@ -20,6 +20,7 @@ | ||
| 20 | 20 | - [improvement] Shuffle the replicas in TokenAwarePolicy.newQueryPlan (JAVA-504) |
| 21 | 21 | - [improvement] Make schema agreement wait tuneable (JAVA-507) |
| 22 | 22 | - [improvement] Document how to inject the driver metrics into another registry (JAVA-494) |
| 23 | +- [improvement] Add idle timeout to the connection pool (JAVA-419) | |
| 23 | 24 | |
| 24 | 25 | |
| 25 | 26 | 2.0.6: |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +15 −0
| @@ -1149,6 +1149,8 @@ | ||
| 1149 | 1149 | |
| 1150 | 1150 | this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this); |
| 1151 | 1151 | this.listeners = new CopyOnWriteArraySet<Host.StateListener>(listeners); |
| 1152 | + | |
| 1153 | + this.scheduledTasksExecutor.scheduleWithFixedDelay(new TrashIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS); | |
| 1152 | 1154 | } |
| 1153 | 1155 | |
| 1154 | 1156 | // Initialization is not too performance intensive and in practice there shouldn't be contention |
| @@ -2104,6 +2106,19 @@ | ||
| 2104 | 2106 | }).start(); |
| 2105 | 2107 | } |
| 2106 | 2108 | } |
| 2109 | + | |
| 2110 | + private class TrashIdleConnectionsTask implements Runnable { | |
| 2111 | + @Override public void run() { | |
| 2112 | + try { | |
| 2113 | + long now = System.currentTimeMillis(); | |
| 2114 | + for (SessionManager session : sessions) { | |
| 2115 | + session.trashIdleConnections(now); | |
| 2116 | + } | |
| 2117 | + } catch (Exception e) { | |
| 2118 | + logger.warn("Error while trashing idle connections", e); | |
| 2119 | + } | |
| 2120 | + } | |
| 2121 | + } | |
| 2107 | 2122 | } |
| 2108 | 2123 | |
| 2109 | 2124 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +14 −8
| @@ -262,15 +262,24 @@ | ||
| 262 | 262 | close(connection); |
| 263 | 263 | } else { |
| 264 | 264 | if (connections.size() > options().getCoreConnectionsPerHost(hostDistance) && inFlight <= options().getMinSimultaneousRequestsPerConnectionThreshold(hostDistance)) { |
| 265 | - trashConnection(connection); | |
| 265 | + connection.setTrashTimeIn(options().getIdleTimeoutSeconds()); | |
| 266 | 266 | } else if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) { |
| 267 | 267 | replaceConnection(connection); |
| 268 | 268 | } else { |
| 269 | + connection.cancelTrashTime(); | |
| 269 | 270 | signalAvailableConnection(); |
| 270 | 271 | } |
| 271 | 272 | } |
| 272 | 273 | } |
| 273 | 274 | |
| 275 | + void trashIdleConnections(long now) { | |
| 276 | + for (PooledConnection connection : connections) { | |
| 277 | + if (connection.getTrashTime() < now) { | |
| 278 | + trashConnection(connection); | |
| 279 | + } | |
| 280 | + } | |
| 281 | + } | |
| 282 | + | |
| 274 | 283 | // Trash the connection and create a new one, but we don't call trashConnection |
| 275 | 284 | // directly because we want to make sure the connection is always trashed. |
| 276 | 285 | private void replaceConnection(PooledConnection connection) { |
| @@ -287,6 +296,7 @@ | ||
| 287 | 296 | int opened = open.get(); |
| 288 | 297 | if (opened <= options().getCoreConnectionsPerHost(hostDistance)) { |
| 289 | 298 | connection.markForTrash.set(false); |
| 299 | + connection.cancelTrashTime(); | |
| 290 | 300 | return false; |
| 291 | 301 | } |
| 292 | 302 | |
| @@ -296,13 +306,9 @@ | ||
| 296 | 306 | |
| 297 | 307 | doTrashConnection(connection); |
| 298 | 308 | } |
| 299 | - // If compareAndSet failed, it means we raced and another thread will execute doTrashConnection. | |
| 300 | - // If the connection needs to be closed (inFlight == 0), we don't need to do it here because the other thread will necessarily do | |
| 301 | - // it: | |
| 302 | - // - the current thread decremented inFlight in returnConnection | |
| 303 | - // - we know it did it before the connection was trashed, because otherwise it would have entered `if (trash.contains(connection))` | |
| 304 | - // in returnConnection and not arrived here. | |
| 305 | - // - so the other thread will see the up-to-date value of inFlight and take appropriate action. | |
| 309 | + // If compareAndSet failed, it means we raced with another thread that will execute doTrashConnection. | |
| 310 | + // Since trashConnection is called from a scheduled task, we're sure that the current thread did not modify | |
| 311 | + // inFlight, so the other thread will take care of closing the connection if necessary (i.e. if inFlight == 0). | |
| 306 | 312 | return true; |
| 307 | 313 | } |
| 308 | 314 |
modified driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +15 −0
| @@ -25,6 +25,9 @@ | ||
| 25 | 25 | |
| 26 | 26 | private final HostConnectionPool pool; |
| 27 | 27 | |
| 28 | + /** The instant when the connection should be trashed after being idle for too long */ | |
| 29 | + private volatile long trashTime = Long.MAX_VALUE; | |
| 30 | + | |
| 28 | 31 | /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */ |
| 29 | 32 | final AtomicBoolean markForTrash = new AtomicBoolean(); |
| 30 | 33 | |
| @@ -60,4 +63,16 @@ | ||
| 60 | 63 | pool.replaceDefunctConnection(this); |
| 61 | 64 | } |
| 62 | 65 | } |
| 66 | + | |
| 67 | + long getTrashTime() { | |
| 68 | + return trashTime; | |
| 69 | + } | |
| 70 | + | |
| 71 | + void cancelTrashTime() { | |
| 72 | + trashTime = Long.MAX_VALUE; | |
| 73 | + } | |
| 74 | + | |
| 75 | + void setTrashTimeIn(int timeoutSeconds) { | |
| 76 | + trashTime = System.currentTimeMillis() + 1000 * timeoutSeconds; | |
| 77 | + } | |
| 63 | 78 | } |
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +31 −0
| @@ -51,6 +51,8 @@ | ||
| 51 | 51 | private static final int DEFAULT_MAX_POOL_LOCAL = 8; |
| 52 | 52 | private static final int DEFAULT_MAX_POOL_REMOTE = 2; |
| 53 | 53 | |
| 54 | + private static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120; | |
| 55 | + | |
| 54 | 56 | private volatile Cluster.Manager manager; |
| 55 | 57 | |
| 56 | 58 | private final int[] minSimultaneousRequests = new int[]{ DEFAULT_MIN_REQUESTS, DEFAULT_MIN_REQUESTS, 0 }; |
| @@ -59,6 +61,8 @@ | ||
| 59 | 61 | private final int[] coreConnections = new int[] { DEFAULT_CORE_POOL_LOCAL, DEFAULT_CORE_POOL_REMOTE, 0 }; |
| 60 | 62 | private final int[] maxConnections = new int[] { DEFAULT_MAX_POOL_LOCAL , DEFAULT_MAX_POOL_REMOTE, 0 }; |
| 61 | 63 | |
| 64 | + private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS; | |
| 65 | + | |
| 62 | 66 | public PoolingOptions() {} |
| 63 | 67 | |
| 64 | 68 | void register(Cluster.Manager manager) { |
| @@ -217,6 +221,33 @@ | ||
| 217 | 221 | return this; |
| 218 | 222 | } |
| 219 | 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 | + | |
| 220 | 251 | /** |
| 221 | 252 | * Requests the driver to re-evaluate the {@link HostDistance} (through the configured |
| 222 | 253 | * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +6 −3
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import java.net.InetAddress; | |
| 19 | 18 | import java.net.InetSocketAddress; |
| 20 | 19 | import java.nio.ByteBuffer; |
| 21 | 20 | import java.util.*; |
| @@ -29,8 +28,6 @@ | ||
| 29 | 28 | import org.slf4j.Logger; |
| 30 | 29 | import org.slf4j.LoggerFactory; |
| 31 | 30 | |
| 32 | - | |
| 33 | -import com.datastax.driver.core.exceptions.AuthenticationException; | |
| 34 | 31 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 35 | 32 | import com.datastax.driver.core.exceptions.UnsupportedFeatureException; |
| 36 | 33 | import com.datastax.driver.core.policies.LoadBalancingPolicy; |
| @@ -506,6 +503,12 @@ | ||
| 506 | 503 | return future; |
| 507 | 504 | } |
| 508 | 505 | |
| 506 | + void trashIdleConnections(long now) { | |
| 507 | + for (HostConnectionPool pool : pools.values()) { | |
| 508 | + pool.trashIdleConnections(now); | |
| 509 | + } | |
| 510 | + } | |
| 511 | + | |
| 509 | 512 | private static class State implements Session.State { |
| 510 | 513 | |
| 511 | 514 | private final SessionManager session; |
added driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTimeoutTest.java +111 −0
| @@ -0,0 +1,111 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.net.InetSocketAddress; | |
| 4 | +import java.util.HashSet; | |
| 5 | +import java.util.Set; | |
| 6 | +import java.util.concurrent.TimeUnit; | |
| 7 | +import java.util.concurrent.atomic.AtomicInteger; | |
| 8 | + | |
| 9 | +import com.codahale.metrics.Gauge; | |
| 10 | +import org.testng.annotations.Test; | |
| 11 | + | |
| 12 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 13 | + | |
| 14 | +public class HostConnectionPoolTimeoutTest { | |
| 15 | + @Test(groups = "long") | |
| 16 | + public void should_wait_for_timeout_before_trashing_connections() throws Exception { | |
| 17 | + CCMBridge ccm = null; | |
| 18 | + Cluster cluster = null; | |
| 19 | + try { | |
| 20 | + ccm = CCMBridge.create("test"); | |
| 21 | + ccm.populate(1); | |
| 22 | + ccm.updateConfig("authenticator", "PasswordAuthenticator"); | |
| 23 | + ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0"); | |
| 24 | + | |
| 25 | + // Hijack the auth provider to be notified each time a connection instance is built | |
| 26 | + CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra"); | |
| 27 | + AtomicInteger createdConnections = authProvider.count; | |
| 28 | + | |
| 29 | + cluster = Cluster.builder() | |
| 30 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 31 | + .withAuthProvider(authProvider) | |
| 32 | + .build(); | |
| 33 | + | |
| 34 | + PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions(); | |
| 35 | + // Set to the max, which makes it slightly easier to reason about when new connections will be created: | |
| 36 | + poolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, 128); | |
| 37 | + int idleTimeoutSeconds = 10; | |
| 38 | + poolingOptions.setIdleTimeoutSeconds(idleTimeoutSeconds); | |
| 39 | + | |
| 40 | + Gauge<Integer> openConnections = cluster.getMetrics().getOpenConnections(); | |
| 41 | + | |
| 42 | + Session session = cluster.connect(); | |
| 43 | + | |
| 44 | + Host host1 = TestUtils.findHost(cluster, 1); | |
| 45 | + HostConnectionPool pool = ((SessionManager)session).pools.get(host1); | |
| 46 | + | |
| 47 | + Set<PooledConnection> coreConnections = new HashSet<PooledConnection>(); | |
| 48 | + | |
| 49 | + // Idle pool: 2 core connections + control connection | |
| 50 | + assertThat(openConnections.getValue()).isEqualTo(3); | |
| 51 | + assertThat(createdConnections.get()).isEqualTo(3); | |
| 52 | + | |
| 53 | + // Max out the two core connections | |
| 54 | + for (int i = 0; i < 2 * 128; i++) { | |
| 55 | + PooledConnection connection = pool.borrowConnection(1, TimeUnit.SECONDS); | |
| 56 | + coreConnections.add(connection); | |
| 57 | + } | |
| 58 | + | |
| 59 | + assertThat(coreConnections).hasSize(2); | |
| 60 | + | |
| 61 | + assertThat(openConnections.getValue()).isEqualTo(3); | |
| 62 | + assertThat(createdConnections.get()).isEqualTo(3); | |
| 63 | + | |
| 64 | + // Borrow one more time, which should spawn a new connection | |
| 65 | + PooledConnection nonCoreConnection = pool.borrowConnection(1, TimeUnit.SECONDS); | |
| 66 | + assertThat(coreConnections).doesNotContain(nonCoreConnection); | |
| 67 | + assertThat(openConnections.getValue()).isEqualTo(4); | |
| 68 | + assertThat(createdConnections.get()).isEqualTo(4); | |
| 69 | + | |
| 70 | + // Return the connection, it should not be trashed immediately | |
| 71 | + pool.returnConnection(nonCoreConnection); | |
| 72 | + TimeUnit.SECONDS.sleep(idleTimeoutSeconds / 2); | |
| 73 | + assertThat(openConnections.getValue()).isEqualTo(4); | |
| 74 | + assertThat(createdConnections.get()).isEqualTo(4); | |
| 75 | + | |
| 76 | + // If we borrow again at this point, it should return the same connection | |
| 77 | + PooledConnection nonCoreConnection2 = pool.borrowConnection(1, TimeUnit.SECONDS); | |
| 78 | + assertThat(nonCoreConnection2).isSameAs(nonCoreConnection); | |
| 79 | + assertThat(openConnections.getValue()).isEqualTo(4); | |
| 80 | + assertThat(createdConnections.get()).isEqualTo(4); | |
| 81 | + | |
| 82 | + // If we return and wait long enough, it should eventually get trashed | |
| 83 | + pool.returnConnection(nonCoreConnection); | |
| 84 | + TimeUnit.SECONDS.sleep(idleTimeoutSeconds * 2); | |
| 85 | + assertThat(openConnections.getValue()).isEqualTo(3); | |
| 86 | + assertThat(createdConnections.get()).isEqualTo(4); | |
| 87 | + | |
| 88 | + } finally { | |
| 89 | + if (cluster != null) | |
| 90 | + cluster.close(); | |
| 91 | + if (ccm != null) | |
| 92 | + ccm.remove(); | |
| 93 | + } | |
| 94 | + } | |
| 95 | + | |
| 96 | + /** | |
| 97 | + * An auth provider that counts how many authenticators it has returned. | |
| 98 | + */ | |
| 99 | + static class CountingAuthProvider extends PlainTextAuthProvider { | |
| 100 | + final AtomicInteger count = new AtomicInteger(); | |
| 101 | + | |
| 102 | + public CountingAuthProvider(String username, String password) { | |
| 103 | + super(username, password); | |
| 104 | + } | |
| 105 | + | |
| 106 | + @Override public Authenticator newAuthenticator(InetSocketAddress host) { | |
| 107 | + count.incrementAndGet(); | |
| 108 | + return super.newAuthenticator(host); | |
| 109 | + } | |
| 110 | + } | |
| 111 | +} | |
| No newline at the end of the file |