Elffuss BraidHub

kikocis/java-driver public

Revert "Add idle timeout to the connection pool (JAVA-419)."

This reverts commits f84cdc1c1b2bfa902528c0c1dc9bbf3cb75c3695,
38edc2e79982e00cc2727b00787054b9a297cc0f and
f5107501c2618acbd17a5ba38b0b310ccddcd7f4.

The implementation needs to be reconsidered (see JAVA-573). Due
to planning constraints, we are not able to address this in 2.0.9. The
feature will be reintroduced in a later version.
Changeset7312842c443e52a69e52a3546d005ecac5c2c156820e561590c1bc92b78f86a9
Authorolim7t <omichallat+github@gmail.com> · 2014-12-15 17:22 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2014-12-15 17:26 +01:00
Parents211e9f833429

Browse the files at this changeset

7 files changed

modified driver-core/CHANGELOG.rst +0 −1
@@ -47,7 +47,6 @@
4747 - [improvement] Shuffle the replicas in TokenAwarePolicy.newQueryPlan (JAVA-504)
4848 - [improvement] Make schema agreement wait tuneable (JAVA-507)
4949 - [improvement] Document how to inject the driver metrics into another registry (JAVA-494)
50-- [improvement] Add idle timeout to the connection pool (JAVA-419)
5150 - [bug] LatencyAwarePolicy does not shutdown executor on invocation of close (JAVA-516)
5251 - [improvement] Throw an exception when DCAwareRoundRobinPolicy is built with
5352 an explicit but null or empty local datacenter (JAVA-451).
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +0 −15
@@ -1161,8 +1161,6 @@
11611161
11621162 this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this);
11631163 this.listeners = new CopyOnWriteArraySet<Host.StateListener>(listeners);
1164-
1165- this.scheduledTasksExecutor.scheduleWithFixedDelay(new TrashIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS);
11661164 }
11671165
11681166 // Initialization is not too performance intensive and in practice there shouldn't be contention
@@ -2175,19 +2173,6 @@
21752173 }).start();
21762174 }
21772175 }
2178-
2179- private class TrashIdleConnectionsTask implements Runnable {
2180- @Override public void run() {
2181- try {
2182- long now = System.currentTimeMillis();
2183- for (SessionManager session : sessions) {
2184- session.trashIdleConnections(now);
2185- }
2186- } catch (Exception e) {
2187- logger.warn("Error while trashing idle connections", e);
2188- }
2189- }
2190- }
21912176 }
21922177
21932178 /**
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +8 −14
@@ -265,24 +265,15 @@
265265 close(connection);
266266 } else {
267267 if (connections.size() > options().getCoreConnectionsPerHost(hostDistance) && inFlight <= options().getMinSimultaneousRequestsPerConnectionThreshold(hostDistance)) {
268- connection.setTrashTimeIn(options().getIdleTimeoutSeconds());
268+ trashConnection(connection);
269269 } else if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) {
270270 replaceConnection(connection);
271271 } else {
272- connection.cancelTrashTime();
273272 signalAvailableConnection();
274273 }
275274 }
276275 }
277276
278- void trashIdleConnections(long now) {
279- for (PooledConnection connection : connections) {
280- if (connection.getTrashTime() < now) {
281- trashConnection(connection);
282- }
283- }
284- }
285-
286277 // Trash the connection and create a new one, but we don't call trashConnection
287278 // directly because we want to make sure the connection is always trashed.
288279 private void replaceConnection(PooledConnection connection) {
@@ -299,7 +290,6 @@
299290 int opened = open.get();
300291 if (opened <= options().getCoreConnectionsPerHost(hostDistance)) {
301292 connection.markForTrash.set(false);
302- connection.cancelTrashTime();
303293 return false;
304294 }
305295
@@ -309,9 +299,13 @@
309299
310300 doTrashConnection(connection);
311301 }
312- // If compareAndSet failed, it means we raced with another thread that will execute doTrashConnection.
313- // Since trashConnection is called from a scheduled task, we're sure that the current thread did not modify
314- // inFlight, so the other thread will take care of closing the connection if necessary (i.e. if inFlight == 0).
302+ // If compareAndSet failed, it means we raced and another thread will execute doTrashConnection.
303+ // If the connection needs to be closed (inFlight == 0), we don't need to do it here because the other thread will necessarily do
304+ // it:
305+ // - the current thread decremented inFlight in returnConnection
306+ // - we know it did it before the connection was trashed, because otherwise it would have entered `if (trash.contains(connection))`
307+ // in returnConnection and not arrived here.
308+ // - so the other thread will see the up-to-date value of inFlight and take appropriate action.
315309 return true;
316310 }
317311
modified driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +0 −15
@@ -25,9 +25,6 @@
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-
3128 /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */
3229 final AtomicBoolean markForTrash = new AtomicBoolean();
3330
@@ -63,16 +60,4 @@
6360 pool.replaceDefunctConnection(this);
6461 }
6562 }
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- }
7863 }
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +0 −29
@@ -51,7 +51,6 @@
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;
5554 private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
5655
5756 private volatile Cluster.Manager manager;
@@ -62,7 +61,6 @@
6261 private final int[] coreConnections = new int[] { DEFAULT_CORE_POOL_LOCAL, DEFAULT_CORE_POOL_REMOTE, 0 };
6362 private final int[] maxConnections = new int[] { DEFAULT_MAX_POOL_LOCAL , DEFAULT_MAX_POOL_REMOTE, 0 };
6463
65- private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
6664 private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
6765
6866 public PoolingOptions() {}
@@ -223,33 +221,6 @@
223221 return this;
224222 }
225223
226- /**
227- * Returns the timeout before an idle connection is removed.
228- *
229- * @return the timeout.
230- */
231- public int getIdleTimeoutSeconds() {
232- return idleTimeoutSeconds;
233- }
234-
235- /**
236- * Sets the timeout before an idle connection is removed.
237- * <p>
238- * The order of magnitude should be a few minutes (the default is 120 seconds). The
239- * timeout that triggers the removal has a granularity of 10 seconds.
240- *
241- * @param idleTimeoutSeconds the new timeout in seconds.
242- * @return this {@code PoolingOptions}.
243- *
244- * @throws IllegalArgumentException if the timeout is negative.
245- */
246- public PoolingOptions setIdleTimeoutSeconds(int idleTimeoutSeconds) {
247- if (idleTimeoutSeconds < 0)
248- throw new IllegalArgumentException("Idle timeout must be positive");
249- this.idleTimeoutSeconds = idleTimeoutSeconds;
250- return this;
251- }
252-
253224 /**
254225 * Returns the timeout when trying to acquire a connection from a host's pool.
255226 *
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +3 −6
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.net.InetAddress;
1819 import java.net.InetSocketAddress;
1920 import java.nio.ByteBuffer;
2021 import java.util.*;
@@ -28,6 +29,8 @@
2829 import org.slf4j.Logger;
2930 import org.slf4j.LoggerFactory;
3031
32+
33+import com.datastax.driver.core.exceptions.AuthenticationException;
3134 import com.datastax.driver.core.exceptions.DriverInternalError;
3235 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
3336 import com.datastax.driver.core.policies.LoadBalancingPolicy;
@@ -540,12 +543,6 @@
540543 return future;
541544 }
542545
543- void trashIdleConnections(long now) {
544- for (HostConnectionPool pool : pools.values()) {
545- pool.trashIdleConnections(now);
546- }
547- }
548-
549546 private static class State implements Session.State {
550547
551548 private final SessionManager session;
deleted driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTimeoutTest.java +0 −181
@@ -1,181 +0,0 @@
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-import com.datastax.driver.core.exceptions.DriverException;
15-import com.datastax.driver.core.exceptions.NoHostAvailableException;
16-
17-public class HostConnectionPoolTimeoutTest {
18- @Test(groups = "long")
19- public void should_wait_for_idle_timeout_before_trashing_connections() throws Exception {
20- CCMBridge ccm = null;
21- Cluster cluster = null;
22- try {
23- ccm = CCMBridge.create("test");
24- ccm.populate(1);
25- ccm.updateConfig("authenticator", "PasswordAuthenticator");
26- ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
27-
28- // Hijack the auth provider to be notified each time a connection instance is built
29- CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra");
30- AtomicInteger createdConnections = authProvider.newAuthenticatorCount;
31-
32- cluster = Cluster.builder()
33- .addContactPoint(CCMBridge.ipOfNode(1))
34- .withAuthProvider(authProvider)
35- .build();
36-
37- PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions();
38- poolingOptions.setMinSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, 1);
39- // Set to the max, which makes it slightly easier to reason about when new connections will be created:
40- poolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, 128);
41- int idleTimeoutSeconds = 10;
42- poolingOptions.setIdleTimeoutSeconds(idleTimeoutSeconds);
43-
44- Gauge<Integer> openConnections = cluster.getMetrics().getOpenConnections();
45-
46- Session session = cluster.connect();
47-
48- Host host1 = TestUtils.findHost(cluster, 1);
49- HostConnectionPool pool = ((SessionManager)session).pools.get(host1);
50-
51- Set<PooledConnection> coreConnections = new HashSet<PooledConnection>();
52-
53- // Idle pool: 2 core connections + control connection
54- assertThat(openConnections.getValue()).isEqualTo(3);
55- assertThat(createdConnections.get()).isEqualTo(3);
56-
57- // Max out the two core connections
58- for (int i = 0; i < 2 * 128; i++) {
59- PooledConnection connection = pool.borrowConnection(1, TimeUnit.SECONDS);
60- coreConnections.add(connection);
61- }
62-
63- assertThat(coreConnections).hasSize(2);
64-
65- assertThat(openConnections.getValue()).isEqualTo(3);
66- assertThat(createdConnections.get()).isEqualTo(3);
67-
68- // Borrow one more stream, which should spawn a new connection
69- PooledConnection nonCoreConnection = pool.borrowConnection(1, TimeUnit.SECONDS);
70- assertThat(coreConnections).doesNotContain(nonCoreConnection);
71- assertThat(openConnections.getValue()).isEqualTo(4);
72- assertThat(createdConnections.get()).isEqualTo(4);
73-
74- // Return the connection, it should not be trashed immediately
75- pool.returnConnection(nonCoreConnection);
76- TimeUnit.SECONDS.sleep(idleTimeoutSeconds / 2);
77- assertThat(openConnections.getValue()).isEqualTo(4);
78- assertThat(createdConnections.get()).isEqualTo(4);
79-
80- // If we borrow again at this point, it should return the same connection
81- PooledConnection nonCoreConnection2 = pool.borrowConnection(1, TimeUnit.SECONDS);
82- assertThat(nonCoreConnection2).isSameAs(nonCoreConnection);
83- assertThat(openConnections.getValue()).isEqualTo(4);
84- assertThat(createdConnections.get()).isEqualTo(4);
85-
86- // Borrow two more and return 1 to reach inFlight = 2 (above the min). The connection should not be trashed.
87- assertThat(pool.borrowConnection(1, TimeUnit.SECONDS)).isSameAs(nonCoreConnection2);
88- assertThat(pool.borrowConnection(1, TimeUnit.SECONDS)).isSameAs(nonCoreConnection2);
89- pool.returnConnection(nonCoreConnection2); // (we need to return one because we cancel the timeout on return)
90- TimeUnit.SECONDS.sleep(idleTimeoutSeconds * 2);
91- assertThat(openConnections.getValue()).isEqualTo(4);
92- assertThat(createdConnections.get()).isEqualTo(4);
93-
94- // Return everything for the non-core connection and wait long enough, it should eventually get trashed
95- pool.returnConnection(nonCoreConnection);
96- pool.returnConnection(nonCoreConnection);
97- TimeUnit.SECONDS.sleep(idleTimeoutSeconds * 2);
98- assertThat(openConnections.getValue()).isEqualTo(3);
99- assertThat(createdConnections.get()).isEqualTo(4);
100-
101- // Return all the streams of the core connections, they should not get trashed
102- for (PooledConnection coreConnection : coreConnections)
103- for (int i = 0; i < 128; i++)
104- pool.returnConnection(coreConnection);
105- assertThat(session.getState().getInFlightQueries(host1)).isEqualTo(0);
106-
107- TimeUnit.SECONDS.sleep(idleTimeoutSeconds * 2);
108- assertThat(openConnections.getValue()).isEqualTo(3);
109- assertThat(createdConnections.get()).isEqualTo(4);
110-
111- } finally {
112- if (cluster != null)
113- cluster.close();
114- if (ccm != null)
115- ccm.remove();
116- }
117- }
118-
119- @Test(groups = "short")
120- public void should_timeout_immediately_if_pool_timeout_is_zero() throws Exception {
121- CCMBridge ccm = null;
122- Cluster cluster = null;
123- try {
124- ccm = CCMBridge.create("test", 1);
125- cluster = Cluster.builder()
126- .addContactPoint(CCMBridge.ipOfNode(1))
127- .build();
128-
129- cluster.getConfiguration().getPoolingOptions()
130- .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
131- .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
132- .setPoolTimeoutMillis(0);
133-
134- Session session = cluster.connect();
135-
136- Host host1 = TestUtils.findHost(cluster, 1);
137-
138- // Borrow all streams to simulate a busy pool (the timeout doesn't matter here)
139- HostConnectionPool pool = ((SessionManager)session).pools.get(host1);
140- for (int i = 0; i < 128; i++)
141- pool.borrowConnection(1, TimeUnit.SECONDS);
142-
143- boolean threw = false;
144- long beforeQuery = System.nanoTime();
145- try {
146- session.execute("select release_version from system.local");
147- } catch (NoHostAvailableException e) {
148- long afterQuery = System.nanoTime();
149- // This is a bit arbitrary, but we can expect that the time to find out there is no available connection
150- // is less than 20 ms
151- assertThat(afterQuery - beforeQuery).isLessThan(20 * 1000 * 1000);
152- Throwable host1Error = e.getErrors().get(host1.getSocketAddress());
153- assertThat(host1Error).isInstanceOf(DriverException.class);
154- assertThat(host1Error.getMessage()).contains("Timeout while trying to acquire available connection");
155- threw = true;
156- }
157- assertThat(threw).isTrue();
158- } finally {
159- if (cluster != null)
160- cluster.close();
161- if (ccm != null)
162- ccm.remove();
163- }
164- }
165-
166- /**
167- * An auth provider that counts how many authenticators it has returned.
168- */
169- static class CountingAuthProvider extends PlainTextAuthProvider {
170- final AtomicInteger newAuthenticatorCount = new AtomicInteger();
171-
172- public CountingAuthProvider(String username, String password) {
173- super(username, password);
174- }
175-
176- @Override public Authenticator newAuthenticator(InetSocketAddress host) {
177- newAuthenticatorCount.incrementAndGet();
178- return super.newAuthenticator(host);
179- }
180- }
181-}
No newline at the end of the file