Elffuss BraidHub

kikocis/java-driver public

Merge PooledConnection into Connection (in preparation for JAVA-505).
Changeset46bcf5126dc2bfc3901d9b2fcf5645f93f37422fe5c2f1392dbc22d831a542e9
Authorolim7t <omichallat+github@gmail.com> · 2014-11-27 11:16 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2014-11-27 18:14 +01:00
Parents9aa18df02350

Browse the files at this changeset

6 files changed

modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +66 −6
@@ -19,6 +19,7 @@
1919 import java.net.InetSocketAddress;
2020 import java.util.Iterator;
2121 import java.util.concurrent.*;
22+import java.util.concurrent.atomic.AtomicBoolean;
2223 import java.util.concurrent.atomic.AtomicInteger;
2324 import java.util.concurrent.atomic.AtomicReference;
2425
@@ -73,6 +74,15 @@
7374
7475 private final Object terminationLock = new Object();
7576
77+
78+ private volatile HostConnectionPool pool;
79+
80+ /** The instant when the connection should be trashed after being idle for too long */
81+ private volatile long trashTime = Long.MAX_VALUE;
82+
83+ /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */
84+ final AtomicBoolean markForTrash = new AtomicBoolean();
85+
7686 /**
7787 * Create a new connection to a Cassandra node.
7888 *
@@ -81,7 +91,7 @@
8191 * @throws ConnectionException if the connection attempts fails or is
8292 * refused by the server.
8393 */
84- protected Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
94+ Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
8595 this.address = address;
8696 this.factory = factory;
8797 this.name = name;
@@ -114,6 +124,16 @@
114124 isInitialized = true;
115125 }
116126
127+ /**
128+ * Create a new connection to a Cassandra node, and associate it to a connection pool.
129+ *
130+ * Note that an existing connection can also be associated to a pool with {@link #setPool(HostConnectionPool)}
131+ */
132+ Connection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
133+ this(name, address, factory);
134+ this.pool = pool;
135+ }
136+
117137 private static String extractMessage(Throwable t) {
118138 if (t == null)
119139 return "";
@@ -265,7 +285,7 @@
265285 // We don't want to signal, because that would invoke triggerOnDown unnecessarily (the host's bad
266286 // condition is already taken care of by the reattempt in progress)
267287 boolean isReconnectionAttempt = (host.state == Host.State.DOWN || host.state == Host.State.SUSPECT)
268- && !(this instanceof PooledConnection);
288+ && (!this.hasPool());
269289 if (!isReconnectionAttempt) {
270290 boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded(), isInitialized);
271291 notifyOwnerWhenDefunct(isDown);
@@ -281,6 +301,14 @@
281301 }
282302
283303 protected void notifyOwnerWhenDefunct(boolean hostIsDown) {
304+ if (pool == null)
305+ return;
306+
307+ if (hostIsDown) {
308+ pool.closeAsync().force();
309+ } else {
310+ pool.replaceDefunctConnection(this);
311+ }
284312 }
285313
286314 public String keyspace() {
@@ -396,6 +424,39 @@
396424 };
397425 }
398426
427+ boolean hasPool() {
428+ return this.pool != null;
429+ }
430+
431+ void setPool(HostConnectionPool pool) {
432+ if (hasPool())
433+ throw new IllegalStateException("cannot move a connection from one pool to another");
434+ this.pool = pool;
435+ }
436+
437+ /**
438+ * If the connection is part of a pool, return it to the pool.
439+ * The connection should generally not be reused after that.
440+ */
441+ void release() {
442+ if (pool == null)
443+ return;
444+
445+ pool.returnConnection(this);
446+ }
447+
448+ long getTrashTime() {
449+ return trashTime;
450+ }
451+
452+ void cancelTrashTime() {
453+ trashTime = Long.MAX_VALUE;
454+ }
455+
456+ void setTrashTimeIn(int timeoutSeconds) {
457+ trashTime = System.currentTimeMillis() + 1000 * timeoutSeconds;
458+ }
459+
399460 public boolean isClosed() {
400461 return closeFuture.get() != null;
401462 }
@@ -512,14 +573,14 @@
512573 /**
513574 * Same as open, but associate the created connection to the provided connection pool.
514575 */
515- public PooledConnection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
576+ public Connection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
516577 InetSocketAddress address = pool.host.getSocketAddress();
517578
518579 if (isShutdown)
519580 throw new ConnectionException(address, "Connection factory is shut down");
520581
521582 String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement();
522- return new PooledConnection(name, address, this, pool);
583+ return new Connection(name, address, this, pool);
523584 }
524585
525586 private AtomicInteger getIdGenerator(Host host) {
@@ -834,8 +895,7 @@
834895 // were, a new request could reuse that ID but get the answer to the request we just gave up on instead
835896 // of its own answer, and we would have no way to detect that.
836897 connection.dispatcher.removeHandler(streamId, false);
837- if (connection instanceof PooledConnection)
838- ((PooledConnection)connection).release();
898+ connection.release();
839899 }
840900
841901 private TimerTask onTimeoutTask() {
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +18 −18
@@ -51,7 +51,7 @@
5151 public volatile HostDistance hostDistance;
5252 private final SessionManager manager;
5353
54- final List<PooledConnection> connections;
54+ final List<Connection> connections;
5555 private final AtomicInteger open;
5656 private final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
5757
@@ -80,7 +80,7 @@
8080 };
8181
8282 // Create initial core connections
83- List<PooledConnection> l = new ArrayList<PooledConnection>(options().getCoreConnectionsPerHost(hostDistance));
83+ List<Connection> l = new ArrayList<Connection>(options().getCoreConnectionsPerHost(hostDistance));
8484 try {
8585 for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++)
8686 l.add(manager.connectionFactory().open(this));
@@ -90,12 +90,12 @@
9090 // But we ignore otherwise cause I'm not sure we can do much better currently.
9191 } catch (RuntimeException e) {
9292 // Rethrow but make sure to properly close the connections in our temporary list.
93- for (PooledConnection connection : l) {
93+ for (Connection connection : l) {
9494 connection.closeAsync().force();
9595 }
9696 throw e;
9797 }
98- this.connections = new CopyOnWriteArrayList<PooledConnection>(l);
98+ this.connections = new CopyOnWriteArrayList<Connection>(l);
9999 this.open = new AtomicInteger(connections.size());
100100
101101 logger.trace("Created connection pool to host {}", host);
@@ -105,7 +105,7 @@
105105 return manager.configuration().getPoolingOptions();
106106 }
107107
108- public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
108+ public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
109109 if (isClosed())
110110 // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
111111 // That being said, maybe having a specific exception could be cleaner.
@@ -118,14 +118,14 @@
118118 scheduledForCreation.incrementAndGet();
119119 manager.blockingExecutor().submit(newConnectionTask);
120120 }
121- PooledConnection c = waitForConnection(timeout, unit);
121+ Connection c = waitForConnection(timeout, unit);
122122 c.setKeyspace(manager.poolsState.keyspace);
123123 return c;
124124 }
125125
126126 int minInFlight = Integer.MAX_VALUE;
127- PooledConnection leastBusy = null;
128- for (PooledConnection connection : connections) {
127+ Connection leastBusy = null;
128+ for (Connection connection : connections) {
129129 int inFlight = connection.inFlight.get();
130130 if (inFlight < minInFlight) {
131131 minInFlight = inFlight;
@@ -198,7 +198,7 @@
198198 }
199199 }
200200
201- private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
201+ private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
202202 if (timeout == 0)
203203 throw new TimeoutException();
204204
@@ -217,8 +217,8 @@
217217 throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
218218
219219 int minInFlight = Integer.MAX_VALUE;
220- PooledConnection leastBusy = null;
221- for (PooledConnection connection : connections) {
220+ Connection leastBusy = null;
221+ for (Connection connection : connections) {
222222 int inFlight = connection.inFlight.get();
223223 if (inFlight < minInFlight) {
224224 minInFlight = inFlight;
@@ -246,7 +246,7 @@
246246 throw new TimeoutException();
247247 }
248248
249- public void returnConnection(PooledConnection connection) {
249+ public void returnConnection(Connection connection) {
250250 if (isClosed()) {
251251 close(connection);
252252 return;
@@ -276,7 +276,7 @@
276276 }
277277
278278 void trashIdleConnections(long now) {
279- for (PooledConnection connection : connections) {
279+ for (Connection connection : connections) {
280280 if (connection.getTrashTime() < now) {
281281 trashConnection(connection);
282282 }
@@ -285,14 +285,14 @@
285285
286286 // Trash the connection and create a new one, but we don't call trashConnection
287287 // directly because we want to make sure the connection is always trashed.
288- private void replaceConnection(PooledConnection connection) {
288+ private void replaceConnection(Connection connection) {
289289 if (connection.markForTrash.compareAndSet(false, true))
290290 open.decrementAndGet();
291291 maybeSpawnNewConnection();
292292 doTrashConnection(connection);
293293 }
294294
295- private boolean trashConnection(PooledConnection connection) {
295+ private boolean trashConnection(Connection connection) {
296296 if (connection.markForTrash.compareAndSet(false, true)) {
297297 // First, make sure we don't go below core connections
298298 for (;;) {
@@ -315,7 +315,7 @@
315315 return true;
316316 }
317317
318- private void doTrashConnection(PooledConnection connection) {
318+ private void doTrashConnection(Connection connection) {
319319 trash.add(connection);
320320 connections.remove(connection);
321321
@@ -384,7 +384,7 @@
384384 manager.blockingExecutor().submit(newConnectionTask);
385385 }
386386
387- void replaceDefunctConnection(final PooledConnection connection) {
387+ void replaceDefunctConnection(final Connection connection) {
388388 if (connection.markForTrash.compareAndSet(false, true))
389389 open.decrementAndGet();
390390 connections.remove(connection);
@@ -431,7 +431,7 @@
431431 return Lists.newArrayList(CloseFuture.immediateFuture());
432432
433433 List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size());
434- for (final PooledConnection connection : connections) {
434+ for (final Connection connection : connections) {
435435 CloseFuture future = connection.closeAsync();
436436 future.addListener(new Runnable() {
437437 public void run() {
deleted driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +0 −78
@@ -1,78 +0,0 @@
1-/*
2- * Copyright (C) 2012-2014 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.InetSocketAddress;
19-import java.util.concurrent.atomic.AtomicBoolean;
20-
21-/**
22- * A connection that is associated to a pool.
23- */
24-class PooledConnection extends Connection {
25-
26- private final HostConnectionPool pool;
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-
31- /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */
32- final AtomicBoolean markForTrash = new AtomicBoolean();
33-
34- PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
35- super(name, address, factory);
36- this.pool = pool;
37- }
38-
39- /**
40- * Return the pooled connection to its pool.
41- * The connection should generally not be reused after that.
42- */
43- public void release() {
44- // This can happen if the query to initialize the transport in the
45- // parent constructor times out. In that case the pool will handle
46- // it itself.
47- if (pool == null)
48- return;
49-
50- pool.returnConnection(this);
51- }
52-
53- @Override
54- protected void notifyOwnerWhenDefunct(boolean hostIsDown) {
55- // This can happen if an exception is thrown at construction time. In
56- // that case the pool will handle it itself.
57- if (pool == null)
58- return;
59-
60- if (hostIsDown) {
61- pool.closeAsync().force();
62- } else {
63- pool.replaceDefunctConnection(this);
64- }
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- }
78-}
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +3 −5
@@ -117,7 +117,7 @@
117117 if (currentPool == null || currentPool.isClosed())
118118 return false;
119119
120- PooledConnection connection = null;
120+ Connection connection = null;
121121 try {
122122 connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS);
123123 if (current != null) {
@@ -263,8 +263,7 @@
263263
264264 Host queriedHost = current;
265265 try {
266- if (connection instanceof PooledConnection)
267- ((PooledConnection)connection).release();
266+ connection.release();
268267
269268 switch (response.type) {
270269 case RESULT:
@@ -522,8 +521,7 @@
522521
523522 Host queriedHost = current;
524523 try {
525- if (connection instanceof PooledConnection)
526- ((PooledConnection)connection).release();
524+ connection.release();
527525
528526 if (exception instanceof ConnectionException) {
529527 if (metricsEnabled())
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +1 −1
@@ -510,7 +510,7 @@
510510
511511 // Let's not wait too long if we can't get a connection. Things
512512 // will fix themselves once the user tries a query anyway.
513- PooledConnection c = null;
513+ Connection c = null;
514514 try {
515515 c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS);
516516 c.write(new Requests.Prepare(query)).get();
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTimeoutTest.java +5 −5
@@ -48,7 +48,7 @@
4848 Host host1 = TestUtils.findHost(cluster, 1);
4949 HostConnectionPool pool = ((SessionManager)session).pools.get(host1);
5050
51- Set<PooledConnection> coreConnections = new HashSet<PooledConnection>();
51+ Set<Connection> coreConnections = new HashSet<Connection>();
5252
5353 // Idle pool: 2 core connections + control connection
5454 assertThat(openConnections.getValue()).isEqualTo(3);
@@ -56,7 +56,7 @@
5656
5757 // Max out the two core connections
5858 for (int i = 0; i < 2 * 128; i++) {
59- PooledConnection connection = pool.borrowConnection(1, TimeUnit.SECONDS);
59+ Connection connection = pool.borrowConnection(1, TimeUnit.SECONDS);
6060 coreConnections.add(connection);
6161 }
6262
@@ -66,7 +66,7 @@
6666 assertThat(createdConnections.get()).isEqualTo(3);
6767
6868 // Borrow one more stream, which should spawn a new connection
69- PooledConnection nonCoreConnection = pool.borrowConnection(1, TimeUnit.SECONDS);
69+ Connection nonCoreConnection = pool.borrowConnection(1, TimeUnit.SECONDS);
7070 assertThat(coreConnections).doesNotContain(nonCoreConnection);
7171 assertThat(openConnections.getValue()).isEqualTo(4);
7272 assertThat(createdConnections.get()).isEqualTo(4);
@@ -78,7 +78,7 @@
7878 assertThat(createdConnections.get()).isEqualTo(4);
7979
8080 // If we borrow again at this point, it should return the same connection
81- PooledConnection nonCoreConnection2 = pool.borrowConnection(1, TimeUnit.SECONDS);
81+ Connection nonCoreConnection2 = pool.borrowConnection(1, TimeUnit.SECONDS);
8282 assertThat(nonCoreConnection2).isSameAs(nonCoreConnection);
8383 assertThat(openConnections.getValue()).isEqualTo(4);
8484 assertThat(createdConnections.get()).isEqualTo(4);
@@ -99,7 +99,7 @@
9999 assertThat(createdConnections.get()).isEqualTo(4);
100100
101101 // Return all the streams of the core connections, they should not get trashed
102- for (PooledConnection coreConnection : coreConnections)
102+ for (Connection coreConnection : coreConnections)
103103 for (int i = 0; i < 128; i++)
104104 pool.returnConnection(coreConnection);
105105 assertThat(session.getState().getInFlightQueries(host1)).isEqualTo(0);