Elffuss BraidHub

kikocis/java-driver public

Add idle timeout to the connection pool (JAVA-419).
Changeset1921aa68332c1f9d852985e5656c97dfabb13684b582a9331d6ae0a287c84fe6
Authorolim7t <omichallat+github@gmail.com> · 2014-10-21 10:26 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2014-10-22 11:53 +02:00
Parentsa6261f6ac1b1

Browse the files at this changeset

7 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -20,6 +20,7 @@
2020 - [improvement] Shuffle the replicas in TokenAwarePolicy.newQueryPlan (JAVA-504)
2121 - [improvement] Make schema agreement wait tuneable (JAVA-507)
2222 - [improvement] Document how to inject the driver metrics into another registry (JAVA-494)
23+- [improvement] Add idle timeout to the connection pool (JAVA-419)
2324
2425
2526 2.0.6:
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +15 −0
@@ -1149,6 +1149,8 @@
11491149
11501150 this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this);
11511151 this.listeners = new CopyOnWriteArraySet<Host.StateListener>(listeners);
1152+
1153+ this.scheduledTasksExecutor.scheduleWithFixedDelay(new TrashIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS);
11521154 }
11531155
11541156 // Initialization is not too performance intensive and in practice there shouldn't be contention
@@ -2104,6 +2106,19 @@
21042106 }).start();
21052107 }
21062108 }
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+ }
21072122 }
21082123
21092124 /**
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +14 −8
@@ -262,15 +262,24 @@
262262 close(connection);
263263 } else {
264264 if (connections.size() > options().getCoreConnectionsPerHost(hostDistance) && inFlight <= options().getMinSimultaneousRequestsPerConnectionThreshold(hostDistance)) {
265- trashConnection(connection);
265+ connection.setTrashTimeIn(options().getIdleTimeoutSeconds());
266266 } else if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) {
267267 replaceConnection(connection);
268268 } else {
269+ connection.cancelTrashTime();
269270 signalAvailableConnection();
270271 }
271272 }
272273 }
273274
275+ void trashIdleConnections(long now) {
276+ for (PooledConnection connection : connections) {
277+ if (connection.getTrashTime() < now) {
278+ trashConnection(connection);
279+ }
280+ }
281+ }
282+
274283 // Trash the connection and create a new one, but we don't call trashConnection
275284 // directly because we want to make sure the connection is always trashed.
276285 private void replaceConnection(PooledConnection connection) {
@@ -287,6 +296,7 @@
287296 int opened = open.get();
288297 if (opened <= options().getCoreConnectionsPerHost(hostDistance)) {
289298 connection.markForTrash.set(false);
299+ connection.cancelTrashTime();
290300 return false;
291301 }
292302
@@ -296,13 +306,9 @@
296306
297307 doTrashConnection(connection);
298308 }
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).
306312 return true;
307313 }
308314
modified driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +15 −0
@@ -25,6 +25,9 @@
2525
2626 private final HostConnectionPool pool;
2727
28+ /** The instant when the connection should be trashed after being idle for too long */
29+ private volatile long trashTime = Long.MAX_VALUE;
30+
2831 /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */
2932 final AtomicBoolean markForTrash = new AtomicBoolean();
3033
@@ -60,4 +63,16 @@
6063 pool.replaceDefunctConnection(this);
6164 }
6265 }
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+ }
6378 }
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +31 −0
@@ -51,6 +51,8 @@
5151 private static final int DEFAULT_MAX_POOL_LOCAL = 8;
5252 private static final int DEFAULT_MAX_POOL_REMOTE = 2;
5353
54+ private static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120;
55+
5456 private volatile Cluster.Manager manager;
5557
5658 private final int[] minSimultaneousRequests = new int[]{ DEFAULT_MIN_REQUESTS, DEFAULT_MIN_REQUESTS, 0 };
@@ -59,6 +61,8 @@
5961 private final int[] coreConnections = new int[] { DEFAULT_CORE_POOL_LOCAL, DEFAULT_CORE_POOL_REMOTE, 0 };
6062 private final int[] maxConnections = new int[] { DEFAULT_MAX_POOL_LOCAL , DEFAULT_MAX_POOL_REMOTE, 0 };
6163
64+ private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
65+
6266 public PoolingOptions() {}
6367
6468 void register(Cluster.Manager manager) {
@@ -217,6 +221,33 @@
217221 return this;
218222 }
219223
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+
220251 /**
221252 * Requests the driver to re-evaluate the {@link HostDistance} (through the configured
222253 * {@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 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
1918 import java.net.InetSocketAddress;
2019 import java.nio.ByteBuffer;
2120 import java.util.*;
@@ -29,8 +28,6 @@
2928 import org.slf4j.Logger;
3029 import org.slf4j.LoggerFactory;
3130
32-
33-import com.datastax.driver.core.exceptions.AuthenticationException;
3431 import com.datastax.driver.core.exceptions.DriverInternalError;
3532 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
3633 import com.datastax.driver.core.policies.LoadBalancingPolicy;
@@ -506,6 +503,12 @@
506503 return future;
507504 }
508505
506+ void trashIdleConnections(long now) {
507+ for (HostConnectionPool pool : pools.values()) {
508+ pool.trashIdleConnections(now);
509+ }
510+ }
511+
509512 private static class State implements Session.State {
510513
511514 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