Elffuss BraidHub

kikocis/java-driver public

Make sure connections are returned to the right pool

JAVA-255 #fixes
Changeset95ffa0094acab1a13c5f1f16c5178765bc47fca6245987c227bf56b85dfe2daf
AuthorSylvain Lebresne <sylvain@datastax.com> · 2014-02-03 17:13 +01:00
CommitterSylvain Lebresne <sylvain@datastax.com> · 2014-02-03 17:15 +01:00
Parents02f35b6b662d

Browse the files at this changeset

6 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -8,6 +8,7 @@
88 - [improvement] Avoid preparing a statement multiple time per host with multiple sessions
99 - [bug] Fix potential thread leaks when shutting down Metrics (JAVA-232)
1010 - [bug] Fix potential NPE in HostConnectionPool (JAVA-231)
11+- [bug] Make sure connections are returned to the right pools (JAVA-255)
1112
1213
1314 1.0.5:
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +14 −1
@@ -96,7 +96,7 @@
9696 * @throws ConnectionException if the connection attempts fails or is
9797 * refused by the server.
9898 */
99- private Connection(String name, InetAddress address, Factory factory) throws ConnectionException, InterruptedException {
99+ protected Connection(String name, InetAddress address, Factory factory) throws ConnectionException, InterruptedException {
100100 super(EMPTY_TRACKER);
101101
102102 this.address = address;
@@ -417,6 +417,19 @@
417417 return new Connection(name, address, this);
418418 }
419419
420+ /**
421+ * Same as open, but associate the created connection to the provided connection pool.
422+ */
423+ public PooledConnection open(HostConnectionPool pool) throws ConnectionException, InterruptedException {
424+ InetAddress address = pool.host.getAddress();
425+
426+ if (isShutdown)
427+ throw new ConnectionException(address, "Connection factory is shut down");
428+
429+ String name = address.toString() + "-" + getIdGenerator(pool.host).getAndIncrement();
430+ return new PooledConnection(name, address, this, pool);
431+ }
432+
420433 private AtomicInteger getIdGenerator(Host host) {
421434 AtomicInteger g = idGenerators.get(host);
422435 if (g == null) {
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +21 −16
@@ -48,7 +48,7 @@
4848 public volatile HostDistance hostDistance;
4949 private final SessionManager manager;
5050
51- private final List<Connection> connections;
51+ private final List<PooledConnection> connections;
5252 private final AtomicInteger open;
5353 private final AtomicBoolean isShutdown = new AtomicBoolean();
5454 private final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
@@ -76,16 +76,16 @@
7676 };
7777
7878 // Create initial core connections
79- List<Connection> l = new ArrayList<Connection>(options().getCoreConnectionsPerHost(hostDistance));
79+ List<PooledConnection> l = new ArrayList<PooledConnection>(options().getCoreConnectionsPerHost(hostDistance));
8080 try {
8181 for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++)
82- l.add(manager.connectionFactory().open(host));
82+ l.add(manager.connectionFactory().open(this));
8383 } catch (InterruptedException e) {
8484 Thread.currentThread().interrupt();
8585 // If asked to interrupt, we can skip opening core connections, the pool will still work.
8686 // But we ignore otherwise cause I'm not sure we can do much better currently.
8787 }
88- this.connections = new CopyOnWriteArrayList<Connection>(l);
88+ this.connections = new CopyOnWriteArrayList<PooledConnection>(l);
8989 this.open = new AtomicInteger(connections.size());
9090
9191 logger.trace("Created connection pool to host {}", host);
@@ -95,7 +95,7 @@
9595 return manager.configuration().getPoolingOptions();
9696 }
9797
98- public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
98+ public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
9999 if (isShutdown.get())
100100 // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
101101 // That being said, maybe having a specific exception could be cleaner.
@@ -108,14 +108,14 @@
108108 scheduledForCreation.incrementAndGet();
109109 manager.blockingExecutor().submit(newConnectionTask);
110110 }
111- Connection c = waitForConnection(timeout, unit);
111+ PooledConnection c = waitForConnection(timeout, unit);
112112 c.setKeyspace(manager.poolsState.keyspace);
113113 return c;
114114 }
115115
116116 int minInFlight = Integer.MAX_VALUE;
117- Connection leastBusy = null;
118- for (Connection connection : connections) {
117+ PooledConnection leastBusy = null;
118+ for (PooledConnection connection : connections) {
119119 int inFlight = connection.inFlight.get();
120120 if (inFlight < minInFlight) {
121121 minInFlight = inFlight;
@@ -188,7 +188,7 @@
188188 }
189189 }
190190
191- private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
191+ private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
192192 long start = System.nanoTime();
193193 long remaining = timeout;
194194 do {
@@ -204,8 +204,8 @@
204204 throw new ConnectionException(host.getAddress(), "Pool is shutdown");
205205
206206 int minInFlight = Integer.MAX_VALUE;
207- Connection leastBusy = null;
208- for (Connection connection : connections) {
207+ PooledConnection leastBusy = null;
208+ for (PooledConnection connection : connections) {
209209 int inFlight = connection.inFlight.get();
210210 if (inFlight < minInFlight) {
211211 minInFlight = inFlight;
@@ -233,7 +233,12 @@
233233 throw new TimeoutException();
234234 }
235235
236- public void returnConnection(Connection connection) {
236+ public void returnConnection(PooledConnection connection) {
237+ if (isShutdown.get()) {
238+ close(connection);
239+ return;
240+ }
241+
237242 int inFlight = connection.inFlight.decrementAndGet();
238243
239244 if (connection.isDefunct()) {
@@ -261,13 +266,13 @@
261266
262267 // Trash the connection and create a new one, but we don't call trashConnection
263268 // directly because we want to make sure the connection is always trashed.
264- private void replaceConnection(Connection connection) {
269+ private void replaceConnection(PooledConnection connection) {
265270 open.decrementAndGet();
266271 maybeSpawnNewConnection();
267272 doTrashConnection(connection);
268273 }
269274
270- private boolean trashConnection(Connection connection) {
275+ private boolean trashConnection(PooledConnection connection) {
271276 // First, make sure we don't go below core connections
272277 for(;;) {
273278 int opened = open.get();
@@ -282,7 +287,7 @@
282287 return true;
283288 }
284289
285- private void doTrashConnection(Connection connection) {
290+ private void doTrashConnection(PooledConnection connection) {
286291 trash.add(connection);
287292 connections.remove(connection);
288293
@@ -309,7 +314,7 @@
309314
310315 // Now really open the connection
311316 try {
312- connections.add(manager.connectionFactory().open(host));
317+ connections.add(manager.connectionFactory().open(this));
313318 signalAvailableConnection();
314319 return true;
315320 } catch (InterruptedException e) {
added driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +40 −0
@@ -0,0 +1,40 @@
1+/*
2+ * Copyright (C) 2012 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.net.InetAddress;
19+
20+/**
21+ * A connection that is associated to a pool.
22+ */
23+class PooledConnection extends Connection {
24+
25+ private final HostConnectionPool pool;
26+
27+ PooledConnection(String name, InetAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException {
28+ super(name, address, factory);
29+ this.pool = pool;
30+ }
31+
32+ /**
33+ * Return the pooled connection to it's pool.
34+ * The connection should generally not be reuse after that.
35+ */
36+ public void release()
37+ {
38+ pool.returnConnection(this);
39+ }
40+}
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +11 −20
@@ -105,7 +105,7 @@
105105 if (currentPool == null || currentPool.isShutdown())
106106 return false;
107107
108- Connection connection = null;
108+ PooledConnection connection = null;
109109 try {
110110 // Note: this is not perfectly correct to use getConnectTimeoutMillis(), but
111111 // until we provide a more fancy to control query timeouts, it's not a bad solution either
@@ -123,13 +123,13 @@
123123 if (metricsEnabled())
124124 metrics().getErrorMetrics().getConnectionErrors().inc();
125125 if (connection != null)
126- currentPool.returnConnection(connection);
126+ connection.release();
127127 logError(host.getAddress(), e.getMessage());
128128 return false;
129129 } catch (BusyConnectionException e) {
130130 // The pool shoudln't have give us a busy connection unless we've maxed up the pool, so move on to the next host.
131131 if (connection != null)
132- currentPool.returnConnection(connection);
132+ connection.release();
133133 logError(host.getAddress(), e.getMessage());
134134 return false;
135135 } catch (TimeoutException e) {
@@ -138,7 +138,7 @@
138138 return false;
139139 } catch (RuntimeException e) {
140140 if (connection != null)
141- currentPool.returnConnection(connection);
141+ connection.release();
142142 logger.error("Unexpected error while querying " + host.getAddress(), e);
143143 logError(host.getAddress(), e.getMessage());
144144 return false;
@@ -216,21 +216,10 @@
216216 callback.onException(connection, exception, System.nanoTime() - startTime);
217217 }
218218
219- private void returnConnection(Connection connection) {
220- // In most case currentPool won't be null since we set it before sending the
221- // query. However, it's possible that for the same write we call both onSet
222- // and onException (especially if a node dies, we'll error out the handler and
223- // that may race with a result that just came in before the death). That fine
224- // though, but it means currentPool might be null (in which case the connection
225- // has been returned already to its pool anyway).
226- if (currentPool != null)
227- currentPool.returnConnection(connection);
228- }
229-
230219 @Override
231220 public void onSet(Connection connection, Message.Response response, long latency) {
232-
233- returnConnection(connection);
221+ if (connection instanceof PooledConnection)
222+ ((PooledConnection)connection).release();
234223
235224 Host queriedHost = current;
236225 try {
@@ -416,8 +405,8 @@
416405
417406 @Override
418407 public void onException(Connection connection, Exception exception, long latency) {
419-
420- returnConnection(connection);
408+ if (connection instanceof PooledConnection)
409+ ((PooledConnection)connection).release();
421410
422411 Host queriedHost = current;
423412 try {
@@ -439,7 +428,9 @@
439428
440429 @Override
441430 public void onTimeout(Connection connection, long latency) {
442- returnConnection(connection);
431+ if (connection instanceof PooledConnection)
432+ ((PooledConnection)connection).release();
433+
443434 Host queriedHost = current;
444435 logError(connection.address, "Timeout during read");
445436 retry(false, null);
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +2 −2
@@ -307,7 +307,7 @@
307307
308308 // Let's not wait too long if we can't get a connection. Things
309309 // will fix themselves once the user tries a query anyway.
310- Connection c = null;
310+ PooledConnection c = null;
311311 try {
312312 c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS);
313313 c.write(new PrepareMessage(query)).get();
@@ -323,7 +323,7 @@
323323 logger.error(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), e);
324324 } finally {
325325 if (c != null)
326- entry.getValue().returnConnection(c);
326+ c.release();
327327 }
328328 }
329329 }