Elffuss BraidHub

kikocis/java-driver public

Optimize connection use on reconnection (JAVA-505).
Changesete646d782bb182fb22523ed34073bfca7642a79fc5e82946c9519276fe6c7ce08
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-04-10 10:22 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-04-17 22:48 +02:00
Parents0a8f5175c6b1

Browse the files at this changeset

10 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -39,6 +39,7 @@
3939 - [new feature] Expose an API to check for schema agreement after a
4040 schema-altering statement (JAVA-669)
4141 - [improvement] Make connection and pool creation fully async (JAVA-692)
42+- [improvement] Optimize connection use after reconnection (JAVA-505)
4243
4344 Merged from 2.0.9_fixes branch:
4445
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +214 −192
@@ -1404,13 +1404,13 @@
14041404 return executor.submit(new ExceptionCatchingRunnable() {
14051405 @Override
14061406 public void runMayThrow() throws InterruptedException, ExecutionException {
1407- onUp(host);
1407+ onUp(host, null);
14081408 }
14091409 });
14101410 }
14111411
14121412 // Use triggerOnUp unless you're sure you want to run this on the current thread.
1413- private void onUp(final Host host) throws InterruptedException, ExecutionException {
1413+ private void onUp(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException {
14141414 logger.debug("Host {} is UP", host);
14151415
14161416 if (isClosed())
@@ -1421,85 +1421,92 @@
14211421 return;
14221422 }
14231423
1424- boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1425- if (!locked) {
1426- logger.warn("Could not acquire notifications lock within {} seconds, ignoring UP notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
1427- return;
1428- }
14291424 try {
14301425
1431- // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
1432- if (host.state == Host.State.UP)
1426+ boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1427+ if (!locked) {
1428+ logger.warn("Could not acquire notifications lock within {} seconds, ignoring UP notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
14331429 return;
1434-
1435- // If there is a reconnection attempt scheduled for that node, cancel it
1436- Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
1437- if (scheduledAttempt != null) {
1438- logger.debug("Cancelling reconnection attempt since node is UP");
1439- scheduledAttempt.cancel(false);
14401430 }
1441-
14421431 try {
1443- prepareAllQueries(host);
1444- } catch (InterruptedException e) {
1445- Thread.currentThread().interrupt();
1446- // Don't propagate because we don't want to prevent other listener to run
1447- } catch (UnsupportedProtocolVersionException e) {
1448- logUnsupportedVersionProtocol(host);
1449- return;
1450- } catch (ClusterNameMismatchException e) {
1451- logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1452- return;
1453- }
1454-
1455- // Session#onUp() expects the load balancing policy to have been updated first, so that
1456- // Host distances are up to date. This mean the policy could return the node before the
1457- // new pool have been created. This is harmless if there is no prior pool since RequestHandler
1458- // will ignore the node, but we do want to make sure there is no prior pool so we don't
1459- // query from a pool we will shutdown right away.
1460- for (SessionManager s : sessions)
1461- s.removePool(host);
1462- loadBalancingPolicy().onUp(host);
1463- controlConnection.onUp(host);
14641432
1465- logger.trace("Adding/renewing host pools for newly UP host {}", host);
1433+ // We don't want to use the public Host.isUp() as this would make us skip the rest for suspected hosts
1434+ if (host.state == Host.State.UP)
1435+ return;
14661436
1467- List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
1468- for (SessionManager s : sessions)
1469- futures.add(s.forceRenewPool(host));
1437+ // If there is a reconnection attempt scheduled for that node, cancel it
1438+ Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
1439+ if (scheduledAttempt != null) {
1440+ logger.debug("Cancelling reconnection attempt since node is UP");
1441+ scheduledAttempt.cancel(false);
1442+ }
14701443
1471- try {
1472- // Only mark the node up once all session have re-added their pool (if the load-balancing
1473- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1474- // to the node.
1475- List<Boolean> poolCreationResults = Futures.allAsList(futures).get();
1476-
1477- // If any of the creation failed, they will have signaled a connection failure
1478- // which will trigger a reconnection to the node. So don't bother marking UP.
1479- if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1480- logger.debug("Connection pool cannot be created, not marking {} UP", host);
1444+ try {
1445+ reusedConnection = prepareAllQueries(host, reusedConnection);
1446+ } catch (InterruptedException e) {
1447+ Thread.currentThread().interrupt();
1448+ // Don't propagate because we don't want to prevent other listener to run
1449+ } catch (UnsupportedProtocolVersionException e) {
1450+ logUnsupportedVersionProtocol(host);
1451+ return;
1452+ } catch (ClusterNameMismatchException e) {
1453+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
14811454 return;
14821455 }
14831456
1484- host.setUp();
1457+ // Session#onUp() expects the load balancing policy to have been updated first, so that
1458+ // Host distances are up to date. This mean the policy could return the node before the
1459+ // new pool have been created. This is harmless if there is no prior pool since RequestHandler
1460+ // will ignore the node, but we do want to make sure there is no prior pool so we don't
1461+ // query from a pool we will shutdown right away.
1462+ for (SessionManager s : sessions)
1463+ s.removePool(host);
1464+ loadBalancingPolicy().onUp(host);
1465+ controlConnection.onUp(host);
1466+
1467+ logger.trace("Adding/renewing host pools for newly UP host {}", host);
1468+
1469+ List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
1470+ for (SessionManager s : sessions)
1471+ futures.add(s.forceRenewPool(host, reusedConnection));
14851472
1486- for (Host.StateListener listener : listeners)
1487- listener.onUp(host);
1473+ try {
1474+ // Only mark the node up once all session have re-added their pool (if the load-balancing
1475+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1476+ // to the node.
1477+ List<Boolean> poolCreationResults = Futures.allAsList(futures).get();
1478+
1479+ // If any of the creation failed, they will have signaled a connection failure
1480+ // which will trigger a reconnection to the node. So don't bother marking UP.
1481+ if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1482+ logger.debug("Connection pool cannot be created, not marking {} UP", host);
1483+ return;
1484+ }
14881485
1489- } catch (ExecutionException e) {
1490- Throwable t = e.getCause();
1491- // That future is not really supposed to throw unexpected exceptions
1492- if (!(t instanceof InterruptedException))
1493- logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
1494- }
1486+ host.setUp();
14951487
1496- // Now, check if there isn't pools to create/remove following the addition.
1497- // We do that now only so that it's not called before we've set the node up.
1498- for (SessionManager s : sessions)
1499- s.updateCreatedPools();
1488+ for (Host.StateListener listener : listeners)
1489+ listener.onUp(host);
1490+
1491+ } catch (ExecutionException e) {
1492+ Throwable t = e.getCause();
1493+ // That future is not really supposed to throw unexpected exceptions
1494+ if (!(t instanceof InterruptedException))
1495+ logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
1496+ }
1497+
1498+ // Now, check if there isn't pools to create/remove following the addition.
1499+ // We do that now only so that it's not called before we've set the node up.
1500+ for (SessionManager s : sessions)
1501+ s.updateCreatedPools();
1502+
1503+ } finally {
1504+ host.notificationsLock.unlock();
1505+ }
15001506
15011507 } finally {
1502- host.notificationsLock.unlock();
1508+ if (reusedConnection != null && !reusedConnection.hasPool())
1509+ reusedConnection.closeAsync();
15031510 }
15041511 }
15051512
@@ -1552,11 +1559,10 @@
15521559 public void runMayThrow() throws InterruptedException, ExecutionException {
15531560 boolean success;
15541561 try {
1555- // TODO: as for the ReconnectionHandler, we could avoid "wasting" this connection
1556- connectionFactory.open(host).closeAsync();
1562+ Connection connection = connectionFactory.open(host);
15571563 // Note that we want to do the pool creation on this thread because we want that
15581564 // when onUp return, the host is ready for querying
1559- onUp(host);
1565+ onUp(host, connection);
15601566 // If one of the connections in onUp failed, it signaled the error and triggerd onDown,
15611567 // but onDown aborted because this reconnection attempt was in progress (JAVA-577).
15621568 // Test the state now to check than onUp succeeded (we know it's up-to-date since onUp was
@@ -1638,7 +1644,6 @@
16381644 if (distance == HostDistance.IGNORED || !startReconnection)
16391645 return;
16401646
1641- // Note: we basically waste the first successful reconnection, but it's probably not a big deal
16421647 logger.debug("{} is down, scheduling connection retries", host);
16431648 startPeriodicReconnectionAttempt(host, isHostAddition);
16441649 } finally {
@@ -1654,19 +1659,15 @@
16541659 }
16551660
16561661 protected void onReconnection(Connection connection) {
1657- // We don't use that first connection so close it.
1658- // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so
1659- // we use it for the first HostConnectionPool created
1660- connection.closeAsync();
16611662 // Make sure we have up-to-date infos on that host before adding it (so we typically
16621663 // catch that an upgraded node uses a new cassandra version).
16631664 if (controlConnection.refreshNodeInfo(host)) {
16641665 logger.debug("Successful reconnection to {}, setting host UP", host);
16651666 try {
16661667 if (isHostAddition)
1667- onAdd(host);
1668+ onAdd(host, connection);
16681669 else
1669- onUp(host);
1670+ onUp(host, connection);
16701671 } catch (InterruptedException e) {
16711672 Thread.currentThread().interrupt();
16721673 } catch (Exception e) {
@@ -1674,6 +1675,7 @@
16741675 }
16751676 } else {
16761677 logger.debug("Not enough info for {}, ignoring host", host);
1678+ connection.closeAsync();
16771679 }
16781680 }
16791681
@@ -1710,16 +1712,12 @@
17101712 }
17111713
17121714 protected void onReconnection(Connection connection) {
1713- // We don't use that first connection so close it.
1714- // TODO: this is a bit wasteful, we should consider passing it to onAdd/onUp so
1715- // we use it for the first HostConnectionPool created
1716- connection.closeAsync();
17171715 // Make sure we have up-to-date infos on that host before adding it (so we typically
17181716 // catch that an upgraded node uses a new cassandra version).
17191717 if (controlConnection.refreshNodeInfo(host)) {
17201718 logger.debug("Successful reconnection to {}, setting host UP", host);
17211719 try {
1722- onUp(host);
1720+ onUp(host, connection);
17231721 } catch (InterruptedException e) {
17241722 Thread.currentThread().interrupt();
17251723 } catch (Exception e) {
@@ -1727,6 +1725,7 @@
17271725 }
17281726 } else {
17291727 logger.debug("Not enough info for {}, ignoring host", host);
1728+ connection.closeAsync();
17301729 }
17311730 }
17321731
@@ -1752,13 +1751,13 @@
17521751 return executor.submit(new ExceptionCatchingRunnable() {
17531752 @Override
17541753 public void runMayThrow() throws InterruptedException, ExecutionException {
1755- onAdd(host);
1754+ onAdd(host, null);
17561755 }
17571756 });
17581757 }
17591758
17601759 // Use triggerOnAdd unless you're sure you want to run this on the current thread.
1761- private void onAdd(final Host host) throws InterruptedException, ExecutionException {
1760+ private void onAdd(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException {
17621761 if (isClosed())
17631762 return;
17641763
@@ -1769,81 +1768,88 @@
17691768 return;
17701769 }
17711770
1772- boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1773- if (!locked) {
1774- logger.warn("Could not acquire notifications lock within {} seconds, ignoring ADD notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
1775- return;
1776- }
17771771 try {
17781772
1779- // Adds to the load balancing first and foremost, as doing so might change the decision
1780- // it will make for distance() on that node (not likely but we leave that possibility).
1781- // This does mean the policy may start returning that node for query plan, but as long
1782- // as no pools have been created (below) this will be ignored by RequestHandler so it's fine.
1783- loadBalancingPolicy().onAdd(host);
1784-
1785- // Next, if the host should be ignored, well, ignore it.
1786- if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1787- // We still mark the node UP though as it should be (and notifiy the listeners).
1788- // We'll mark it down if we have a notification anyway and we've documented that especially
1789- // for IGNORED hosts, the isUp() method was a best effort guess
1790- host.setUp();
1791- for (Host.StateListener listener : listeners)
1792- listener.onAdd(host);
1773+ boolean locked = host.notificationsLock.tryLock(NOTIF_LOCK_TIMEOUT_SECONDS, TimeUnit.SECONDS);
1774+ if (!locked) {
1775+ logger.warn("Could not acquire notifications lock within {} seconds, ignoring ADD notification for {}", NOTIF_LOCK_TIMEOUT_SECONDS, host);
17931776 return;
17941777 }
1795-
17961778 try {
1797- prepareAllQueries(host);
1798- } catch (InterruptedException e) {
1799- Thread.currentThread().interrupt();
1800- // Don't propagate because we don't want to prevent other listener to run
1801- } catch (UnsupportedProtocolVersionException e) {
1802- logUnsupportedVersionProtocol(host);
1803- return;
1804- } catch (ClusterNameMismatchException e) {
1805- logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
1806- return;
1807- }
1808-
1809- controlConnection.onAdd(host);
18101779
1811- List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
1812- for (SessionManager s : sessions)
1813- futures.add(s.maybeAddPool(host));
1780+ // Adds to the load balancing first and foremost, as doing so might change the decision
1781+ // it will make for distance() on that node (not likely but we leave that possibility).
1782+ // This does mean the policy may start returning that node for query plan, but as long
1783+ // as no pools have been created (below) this will be ignored by RequestHandler so it's fine.
1784+ loadBalancingPolicy().onAdd(host);
1785+
1786+ // Next, if the host should be ignored, well, ignore it.
1787+ if (loadBalancingPolicy().distance(host) == HostDistance.IGNORED) {
1788+ // We still mark the node UP though as it should be (and notifiy the listeners).
1789+ // We'll mark it down if we have a notification anyway and we've documented that especially
1790+ // for IGNORED hosts, the isUp() method was a best effort guess
1791+ host.setUp();
1792+ for (Host.StateListener listener : listeners)
1793+ listener.onAdd(host);
1794+ return;
1795+ }
18141796
1815- try {
1816- // Only mark the node up once all session have added their pool (if the load-balancing
1817- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1818- // to the node.
1819- List<Boolean> poolCreationResults = Futures.allAsList(futures).get();
1820-
1821- // If any of the creation failed, they will have signaled a connection failure
1822- // which will trigger a reconnection to the node. So don't bother marking UP.
1823- if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1824- logger.debug("Connection pool cannot be created, not marking {} UP", host);
1797+ try {
1798+ reusedConnection = prepareAllQueries(host, reusedConnection);
1799+ } catch (InterruptedException e) {
1800+ Thread.currentThread().interrupt();
1801+ // Don't propagate because we don't want to prevent other listener to run
1802+ } catch (UnsupportedProtocolVersionException e) {
1803+ logUnsupportedVersionProtocol(host);
1804+ return;
1805+ } catch (ClusterNameMismatchException e) {
1806+ logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
18251807 return;
18261808 }
18271809
1828- host.setUp();
1810+ controlConnection.onAdd(host);
18291811
1830- for (Host.StateListener listener : listeners)
1831- listener.onAdd(host);
1812+ List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
1813+ for (SessionManager s : sessions)
1814+ futures.add(s.maybeAddPool(host, reusedConnection));
18321815
1833- } catch (ExecutionException e) {
1834- Throwable t = e.getCause();
1835- // That future is not really supposed to throw unexpected exceptions
1836- if (!(t instanceof InterruptedException))
1837- logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
1838- }
1816+ try {
1817+ // Only mark the node up once all session have added their pool (if the load-balancing
1818+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1819+ // to the node.
1820+ List<Boolean> poolCreationResults = Futures.allAsList(futures).get();
1821+
1822+ // If any of the creation failed, they will have signaled a connection failure
1823+ // which will trigger a reconnection to the node. So don't bother marking UP.
1824+ if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1825+ logger.debug("Connection pool cannot be created, not marking {} UP", host);
1826+ return;
1827+ }
18391828
1840- // Now, check if there isn't pools to create/remove following the addition.
1841- // We do that now only so that it's not called before we've set the node up.
1842- for (SessionManager s : sessions)
1843- s.updateCreatedPools();
1829+ host.setUp();
1830+
1831+ for (Host.StateListener listener : listeners)
1832+ listener.onAdd(host);
1833+
1834+ } catch (ExecutionException e) {
1835+ Throwable t = e.getCause();
1836+ // That future is not really supposed to throw unexpected exceptions
1837+ if (!(t instanceof InterruptedException))
1838+ logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
1839+ }
1840+
1841+ // Now, check if there isn't pools to create/remove following the addition.
1842+ // We do that now only so that it's not called before we've set the node up.
1843+ for (SessionManager s : sessions)
1844+ s.updateCreatedPools();
1845+
1846+ } finally {
1847+ host.notificationsLock.unlock();
1848+ }
18441849
18451850 } finally {
1846- host.notificationsLock.unlock();
1851+ if (reusedConnection != null && !reusedConnection.hasPool())
1852+ reusedConnection.closeAsync();
18471853 }
18481854 }
18491855
@@ -1942,69 +1948,85 @@
19421948 return stmt;
19431949 }
19441950
1945- private void prepareAllQueries(Host host) throws InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
1951+ /**
1952+ * @param reusedConnection an existing connection (from a reconnection attempt) that we want to
1953+ * reuse to prepare the statements (might be null).
1954+ * @return a connection that the rest of the initialization process can use (it will be made part
1955+ * of a connection pool). Can be reusedConnection, or one that was open in the method.
1956+ */
1957+ private Connection prepareAllQueries(Host host, Connection reusedConnection) throws InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
19461958 if (preparedQueries.isEmpty())
1947- return;
1959+ return reusedConnection;
19481960
19491961 logger.debug("Preparing {} prepared queries on newly up node {}", preparedQueries.size(), host);
1962+ Connection connection = null;
19501963 try {
1951- Connection connection = connectionFactory.open(host);
1964+ connection = (reusedConnection == null)
1965+ ? connectionFactory.open(host)
1966+ : reusedConnection;
19521967
1953- try
1954- {
1955- try {
1956- ControlConnection.waitForSchemaAgreement(connection, this);
1957- } catch (ExecutionException e) {
1958- // As below, just move on
1959- }
1968+ try {
1969+ ControlConnection.waitForSchemaAgreement(connection, this);
1970+ } catch (ExecutionException e) {
1971+ // As below, just move on
1972+ }
19601973
1961- // Furthermore, along with each prepared query we keep the current keyspace at the time of preparation
1962- // as we need to make it is the same when we re-prepare on new/restarted nodes. Most query will use the
1963- // same keyspace so keeping it each time is slightly wasteful, but this doesn't really matter and is
1964- // simpler. Besides, we do avoid in prepareAllQueries to not set the current keyspace more than needed.
1965-
1966- // We need to make sure we prepared every query with the right current keyspace, i.e. the one originally
1967- // used for preparing it. However, since we are likely that all prepared query belong to only a handful
1968- // of different keyspace (possibly only one), and to avoid setting the current keyspace more than needed,
1969- // we first sort the query per keyspace.
1970- SetMultimap<String, String> perKeyspace = HashMultimap.create();
1971- for (PreparedStatement ps : preparedQueries.values()) {
1972- // It's possible for a query to not have a current keyspace. But since null doesn't work well as
1973- // map keys, we use the empty string instead (that is not a valid keyspace name).
1974- String keyspace = ps.getQueryKeyspace() == null ? "" : ps.getQueryKeyspace();
1975- perKeyspace.put(keyspace, ps.getQueryString());
1976- }
1974+ // Furthermore, along with each prepared query we keep the current keyspace at the time of preparation
1975+ // as we need to make it is the same when we re-prepare on new/restarted nodes. Most query will use the
1976+ // same keyspace so keeping it each time is slightly wasteful, but this doesn't really matter and is
1977+ // simpler. Besides, we do avoid in prepareAllQueries to not set the current keyspace more than needed.
1978+
1979+ // We need to make sure we prepared every query with the right current keyspace, i.e. the one originally
1980+ // used for preparing it. However, since we are likely that all prepared query belong to only a handful
1981+ // of different keyspace (possibly only one), and to avoid setting the current keyspace more than needed,
1982+ // we first sort the query per keyspace.
1983+ SetMultimap<String, String> perKeyspace = HashMultimap.create();
1984+ for (PreparedStatement ps : preparedQueries.values()) {
1985+ // It's possible for a query to not have a current keyspace. But since null doesn't work well as
1986+ // map keys, we use the empty string instead (that is not a valid keyspace name).
1987+ String keyspace = ps.getQueryKeyspace() == null ? "" : ps.getQueryKeyspace();
1988+ perKeyspace.put(keyspace, ps.getQueryString());
1989+ }
19771990
1978- for (String keyspace : perKeyspace.keySet())
1979- {
1980- // Empty string mean no particular keyspace to set
1981- if (!keyspace.isEmpty())
1982- connection.setKeyspace(keyspace);
1983-
1984- List<Connection.Future> futures = new ArrayList<Connection.Future>(preparedQueries.size());
1985- for (String query : perKeyspace.get(keyspace)) {
1986- futures.add(connection.write(new Requests.Prepare(query)));
1987- }
1988- for (Connection.Future future : futures) {
1989- try {
1990- future.get();
1991- } catch (ExecutionException e) {
1992- // This "might" happen if we drop a CF but haven't removed it's prepared queries (which we don't do
1993- // currently). It's not a big deal however as if it's a more serious problem it'll show up later when
1994- // the query is tried for execution.
1995- logger.debug("Unexpected error while preparing queries on new/newly up host", e);
1996- }
1991+ for (String keyspace : perKeyspace.keySet()) {
1992+ // Empty string mean no particular keyspace to set
1993+ if (!keyspace.isEmpty())
1994+ connection.setKeyspace(keyspace);
1995+
1996+ List<Connection.Future> futures = new ArrayList<Connection.Future>(preparedQueries.size());
1997+ for (String query : perKeyspace.get(keyspace)) {
1998+ futures.add(connection.write(new Requests.Prepare(query)));
1999+ }
2000+ for (Connection.Future future : futures) {
2001+ try {
2002+ future.get();
2003+ } catch (ExecutionException e) {
2004+ // This "might" happen if we drop a CF but haven't removed it's prepared queries (which we don't do
2005+ // currently). It's not a big deal however as if it's a more serious problem it'll show up later when
2006+ // the query is tried for execution.
2007+ logger.debug("Unexpected error while preparing queries on new/newly up host", e);
19972008 }
19982009 }
1999- } finally {
2000- connection.closeAsync();
20012010 }
2011+
2012+ return connection;
20022013 } catch (ConnectionException e) {
20032014 // Ignore, not a big deal
2015+ if (connection != null)
2016+ connection.closeAsync();
2017+ return null;
20042018 } catch (AuthenticationException e) {
20052019 // That's a bad news, but ignore at this point
2020+ if (connection != null)
2021+ connection.closeAsync();
2022+ return null;
20062023 } catch (BusyConnectionException e) {
20072024 // Ignore, not a big deal
2025+ // In theory the problem is transient so the connection could be reused later, but if the core pool size is 1
2026+ // it's better to close this one so that we start with a fresh connection.
2027+ if (connection != null)
2028+ connection.closeAsync();
2029+ return null;
20082030 }
20092031 }
20102032
@@ -2093,7 +2115,7 @@
20932115 // Make sure we have up-to-date infos on that host before adding it (so we typically
20942116 // catch that an upgraded node uses a new cassandra version).
20952117 if (controlConnection.refreshNodeInfo(newHost)) {
2096- onAdd(newHost);
2118+ onAdd(newHost, null);
20972119 } else {
20982120 logger.debug("Not enough info for {}, ignoring host", newHost);
20992121 }
@@ -2135,7 +2157,7 @@
21352157 // Make sure we have up-to-date infos on that host before adding it (so we typically
21362158 // catch that an upgraded node uses a new cassandra version).
21372159 if (controlConnection.refreshNodeInfo(h)) {
2138- onAdd(h);
2160+ onAdd(h, null);
21392161 } else {
21402162 logger.debug("Not enough info for {}, ignoring host", h);
21412163 }
@@ -2148,7 +2170,7 @@
21482170 // Make sure we have up-to-date infos on that host before adding it (so we typically
21492171 // catch that an upgraded node uses a new cassandra version).
21502172 if (controlConnection.refreshNodeInfo(hostUp)) {
2151- onUp(hostUp);
2173+ onUp(hostUp, null);
21522174 } else {
21532175 logger.debug("Not enough info for {}, ignoring host", hostUp);
21542176 }
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +64 −12
@@ -65,6 +65,12 @@
6565
6666 private static final boolean DISABLE_COALESCING = SystemProperties.getBoolean("com.datastax.driver.DISABLE_COALESCING", false);
6767
68+ enum State {OPEN, TRASHED, RESURRECTING, GONE }
69+
70+ final AtomicReference<State> state = new AtomicReference<State>(State.OPEN);
71+
72+ volatile long maxIdleTime;
73+
6874 public final InetSocketAddress address;
6975 private final String name;
7076
@@ -84,15 +90,30 @@
8490
8591 private final AtomicReference<ConnectionCloseFuture> closeFuture = new AtomicReference<ConnectionCloseFuture>();
8692
93+ private final AtomicReference<HostConnectionPool> poolRef = new AtomicReference<HostConnectionPool>();
94+
8795 /**
88- * Create a new connection to a Cassandra node.
96+ /**
97+ * Create a new connection to a Cassandra node and associate it with the given pool.
8998 *
90- * The connection is open and initialized by the constructor.
99+ * @param name the connection name
100+ * @param address the remote address
101+ * @param factory the connection factory to use
102+ * @param pool the pool this connection belongs to. May be null if this connection does not belong to a pool.
103+ * Note that an existing connection can also be associated to a pool later with {@link #setPool(HostConnectionPool)}.
91104 */
92- protected Connection(String name, InetSocketAddress address, Factory factory) {
105+ protected Connection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) {
93106 this.address = address;
94107 this.factory = factory;
95108 this.name = name;
109+ this.poolRef.set(pool);
110+ }
111+
112+ /**
113+ * Create a new connection to a Cassandra node.
114+ */
115+ Connection(String name, InetSocketAddress address, Factory factory) {
116+ this(name, address, factory, null);
96117 }
97118
98119 public ListenableFuture<Void> initAsync() {
@@ -377,9 +398,9 @@
377398 // If the host was reconnecting, and this error happens right after we opened a connection pool, but
378399 // before we could mark the node UP, we don't want to go through the SUSPECTED state, because that can
379400 // lead to a race condition that leaves the node UP with a closed pool.
401+ HostConnectionPool pool = this.poolRef.get();
380402 boolean belongsToReconnectingPool = host.state != Host.State.UP &&
381- this instanceof PooledConnection &&
382- (((PooledConnection)this).pool == null || !((PooledConnection)this).pool.isClosed());
403+ (pool == null || !pool.isClosed());
383404
384405 boolean markSuspected = isInitialized && !belongsToReconnectingPool;
385406
@@ -398,6 +419,19 @@
398419 }
399420
400421 protected void notifyOwnerWhenDefunct(boolean hostIsDown) {
422+ // If an error happens during initialization, the owner will detect it and take appropriate action
423+ if (!isInitialized)
424+ return;
425+
426+ HostConnectionPool pool = this.poolRef.get();
427+ if (pool == null)
428+ return;
429+
430+ if (hostIsDown) {
431+ pool.closeAsync().force();
432+ } else {
433+ pool.replaceDefunctConnection(this);
434+ }
401435 }
402436
403437 public String keyspace() {
@@ -546,6 +580,25 @@
546580 };
547581 }
548582
583+ boolean hasPool() {
584+ return this.poolRef.get() != null;
585+ }
586+
587+ /** @return whether the connection was already associated with a pool */
588+ boolean setPool(HostConnectionPool pool) {
589+ return poolRef.compareAndSet(null, pool);
590+ }
591+
592+ /**
593+ * If the connection is part of a pool, return it to the pool.
594+ * The connection should generally not be reused after that.
595+ */
596+ void release() {
597+ HostConnectionPool pool = poolRef.get();
598+ if (pool != null)
599+ pool.returnConnection(this);
600+ }
601+
549602 public boolean isClosed() {
550603 return closeFuture.get() != null;
551604 }
@@ -682,9 +735,9 @@
682735 /**
683736 * Same as open, but associate the created connection to the provided connection pool.
684737 */
685- public PooledConnection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
738+ public Connection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
686739 try {
687- PooledConnection connection = newConnection(pool);
740+ Connection connection = newConnection(pool);
688741 connection.initAsync().get();
689742 return connection;
690743 } catch (ExecutionException e) {
@@ -695,11 +748,11 @@
695748 /**
696749 * Creates a new connection and associates it to the provided connection pool, but does not start it.
697750 */
698- public PooledConnection newConnection(HostConnectionPool pool) {
751+ public Connection newConnection(HostConnectionPool pool) {
699752 InetSocketAddress address = pool.host.getSocketAddress();
700753 String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement();
701754
702- return new PooledConnection(name, address, this, pool);
755+ return new Connection(name, address, this, pool);
703756 }
704757
705758 static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
@@ -844,7 +897,7 @@
844897 }
845898
846899 private static final ConcurrentMap<EventLoop, Flusher> flusherLookup = new MapMaker()
847- .concurrencyLevel(16)
900+ .concurrencyLevel(16)
848901 .weakKeys()
849902 .makeMap();
850903
@@ -1181,8 +1234,7 @@
11811234 // were, a new request could reuse that ID but get the answer to the request we just gave up on instead
11821235 // of its own answer, and we would have no way to detect that.
11831236 connection.dispatcher.removeHandler(this, false);
1184- if (connection instanceof PooledConnection)
1185- ((PooledConnection)connection).release();
1237+ connection.release();
11861238 }
11871239
11881240 private TimerTask onTimeoutTask() {
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +51 −35
@@ -31,11 +31,12 @@
3131 import org.slf4j.LoggerFactory;
3232
3333 import com.datastax.driver.core.exceptions.AuthenticationException;
34+import com.datastax.driver.core.utils.MoreFutures;
3435
35-import static com.datastax.driver.core.PooledConnection.State.GONE;
36-import static com.datastax.driver.core.PooledConnection.State.OPEN;
37-import static com.datastax.driver.core.PooledConnection.State.RESURRECTING;
38-import static com.datastax.driver.core.PooledConnection.State.TRASHED;
36+import static com.datastax.driver.core.Connection.State.GONE;
37+import static com.datastax.driver.core.Connection.State.OPEN;
38+import static com.datastax.driver.core.Connection.State.RESURRECTING;
39+import static com.datastax.driver.core.Connection.State.TRASHED;
3940
4041 class HostConnectionPool {
4142
@@ -52,13 +53,13 @@
5253 public volatile HostDistance hostDistance;
5354 private final SessionManager manager;
5455
55- final List<PooledConnection> connections;
56+ final List<Connection> connections;
5657 private final AtomicInteger open;
5758 /** The total number of in-flight requests on all connections of this pool. */
5859 final AtomicInteger totalInFlight = new AtomicInteger();
5960 /** The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}*/
6061 private final AtomicInteger maxTotalInFlight = new AtomicInteger();
61- final Set<PooledConnection> trash = new CopyOnWriteArraySet<PooledConnection>();
62+ final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
6263
6364 private volatile int waiter = 0;
6465 private final Lock waitLock = new ReentrantLock(true);
@@ -73,7 +74,7 @@
7374 private enum Phase { INITIALIZING, READY, INIT_FAILED, CLOSING }
7475 private volatile Phase phase = Phase.INITIALIZING;
7576
76- public HostConnectionPool(final Host host, HostDistance hostDistance, final SessionManager manager) {
77+ public HostConnectionPool(final Host host, HostDistance hostDistance, final SessionManager manager){
7778 assert hostDistance != HostDistance.IGNORED;
7879 this.host = host;
7980 this.hostDistance = hostDistance;
@@ -87,19 +88,34 @@
8788 }
8889 };
8990
90- this.connections = new CopyOnWriteArrayList<PooledConnection>();
91+ this.connections = new CopyOnWriteArrayList<Connection>();
9192 this.open = new AtomicInteger();
9293 }
9394
94- public ListenableFuture<Void> initAsync() {
95+ /**
96+ * @param reusedConnection an existing connection (from a reconnection attempt) that we want to
97+ * reuse as part of this pool. Might be null or already used by another
98+ * pool.
99+ */
100+ public ListenableFuture<Void> initAsync(Connection reusedConnection) {
95101 // Create initial core connections
96102 int capacity = options().getCoreConnectionsPerHost(hostDistance);
97- final List<PooledConnection> connections = Lists.newArrayListWithCapacity(capacity);
103+ final List<Connection> connections = Lists.newArrayListWithCapacity(capacity);
98104 final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(capacity);
99- for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
100- PooledConnection connection = manager.connectionFactory().newConnection(this);
105+ for (int i = 0; i < capacity; i++) {
106+ Connection connection;
107+ ListenableFuture<Void> connectionFuture;
108+ // reuse the existing connection only once
109+ if (reusedConnection != null && reusedConnection.setPool(this)) {
110+ connection = reusedConnection;
111+ connectionFuture = MoreFutures.VOID_SUCCESS;
112+ } else {
113+ connection = manager.connectionFactory().newConnection(this);
114+ connectionFuture = connection.initAsync();
115+ }
116+ reusedConnection = null;
101117 connections.add(connection);
102- connectionFutures.add(connection.initAsync());
118+ connectionFutures.add(connectionFuture);
103119 }
104120
105121 Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
@@ -134,8 +150,8 @@
134150 }
135151
136152 // Clean up if we got an error at construction time but still created part of the core connections
137- private void forceClose(List<PooledConnection> connections) {
138- for (PooledConnection connection : connections) {
153+ private void forceClose(List<Connection> connections) {
154+ for (Connection connection : connections) {
139155 connection.closeAsync().force();
140156 }
141157 }
@@ -144,7 +160,7 @@
144160 return manager.configuration().getPoolingOptions();
145161 }
146162
147- public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
163+ public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
148164 if (phase == Phase.INITIALIZING)
149165 throw new ConnectionException(host.getSocketAddress(), "Pool is initializing.");
150166
@@ -160,15 +176,15 @@
160176 scheduledForCreation.incrementAndGet();
161177 manager.blockingExecutor().submit(newConnectionTask);
162178 }
163- PooledConnection c = waitForConnection(timeout, unit);
179+ Connection c = waitForConnection(timeout, unit);
164180 totalInFlight.incrementAndGet();
165181 c.setKeyspace(manager.poolsState.keyspace);
166182 return c;
167183 }
168184
169185 int minInFlight = Integer.MAX_VALUE;
170- PooledConnection leastBusy = null;
171- for (PooledConnection connection : connections) {
186+ Connection leastBusy = null;
187+ for (Connection connection : connections) {
172188 int inFlight = connection.inFlight.get();
173189 if (inFlight < minInFlight) {
174190 minInFlight = inFlight;
@@ -256,7 +272,7 @@
256272 }
257273 }
258274
259- private PooledConnection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
275+ private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
260276 if (timeout == 0)
261277 throw new TimeoutException();
262278
@@ -275,8 +291,8 @@
275291 throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
276292
277293 int minInFlight = Integer.MAX_VALUE;
278- PooledConnection leastBusy = null;
279- for (PooledConnection connection : connections) {
294+ Connection leastBusy = null;
295+ for (Connection connection : connections) {
280296 int inFlight = connection.inFlight.get();
281297 if (inFlight < minInFlight) {
282298 minInFlight = inFlight;
@@ -304,7 +320,7 @@
304320 throw new TimeoutException();
305321 }
306322
307- public void returnConnection(PooledConnection connection) {
323+ public void returnConnection(Connection connection) {
308324 connection.inFlight.decrementAndGet();
309325 totalInFlight.decrementAndGet();
310326
@@ -330,7 +346,7 @@
330346
331347 // Trash the connection and create a new one, but we don't call trashConnection
332348 // directly because we want to make sure the connection is always trashed.
333- private void replaceConnection(PooledConnection connection) {
349+ private void replaceConnection(Connection connection) {
334350 if (!connection.state.compareAndSet(OPEN, TRASHED))
335351 return;
336352 open.decrementAndGet();
@@ -339,7 +355,7 @@
339355 doTrashConnection(connection);
340356 }
341357
342- private boolean trashConnection(PooledConnection connection) {
358+ private boolean trashConnection(Connection connection) {
343359 if (!connection.state.compareAndSet(OPEN, TRASHED))
344360 return true;
345361
@@ -360,7 +376,7 @@
360376 return true;
361377 }
362378
363- private void doTrashConnection(PooledConnection connection) {
379+ private void doTrashConnection(Connection connection) {
364380 connections.remove(connection);
365381 trash.add(connection);
366382 }
@@ -384,7 +400,7 @@
384400
385401 // Now really open the connection
386402 try {
387- PooledConnection newConnection = tryResurrectFromTrash();
403+ Connection newConnection = tryResurrectFromTrash();
388404 if (newConnection == null) {
389405 logger.debug("Creating new connection on busy pool to {}", host);
390406 newConnection = manager.connectionFactory().open(this);
@@ -428,12 +444,12 @@
428444 }
429445 }
430446
431- private PooledConnection tryResurrectFromTrash() {
447+ private Connection tryResurrectFromTrash() {
432448 long highestMaxIdleTime = System.currentTimeMillis();
433- PooledConnection chosen = null;
449+ Connection chosen = null;
434450
435451 while (true) {
436- for (PooledConnection connection : trash)
452+ for (Connection connection : trash)
437453 if (connection.maxIdleTime > highestMaxIdleTime && connection.maxAvailableStreams() > MIN_AVAILABLE_STREAMS) {
438454 chosen = connection;
439455 highestMaxIdleTime = connection.maxIdleTime;
@@ -461,7 +477,7 @@
461477 manager.blockingExecutor().submit(newConnectionTask);
462478 }
463479
464- void replaceDefunctConnection(final PooledConnection connection) {
480+ void replaceDefunctConnection(final Connection connection) {
465481 if (connection.state.compareAndSet(OPEN, GONE))
466482 open.decrementAndGet();
467483 if (connections.remove(connection))
@@ -499,7 +515,7 @@
499515 if (toTrash <= 0)
500516 return;
501517
502- for (PooledConnection connection : connections)
518+ for (Connection connection : connections)
503519 if (trashConnection(connection)) {
504520 toTrash -= 1;
505521 if (toTrash == 0)
@@ -509,7 +525,7 @@
509525
510526 /** Close connections that have been sitting in the trash for too long */
511527 private void cleanupTrash(long now) {
512- for (PooledConnection connection : trash) {
528+ for (Connection connection : trash) {
513529 if (connection.maxIdleTime < now && connection.state.compareAndSet(TRASHED, GONE)) {
514530 if (connection.inFlight.get() == 0) {
515531 logger.trace("Cleaning up {}", connection);
@@ -565,7 +581,7 @@
565581
566582 List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size());
567583
568- for (final PooledConnection connection : connections) {
584+ for (final Connection connection : connections) {
569585 CloseFuture future = connection.closeAsync();
570586 future.addListener(new Runnable() {
571587 public void run() {
@@ -577,7 +593,7 @@
577593 }
578594
579595 // Some connections in the trash might still be open if they hadn't reached their idle timeout
580- for (PooledConnection connection : trash)
596+ for (Connection connection : trash)
581597 futures.add(connection.closeAsync());
582598
583599 return futures;
deleted driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +0 −66
@@ -1,66 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 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.AtomicReference;
20-
21-/**
22- * A connection that is associated to a pool.
23- */
24-class PooledConnection extends Connection {
25-
26- final HostConnectionPool pool;
27-
28- enum State {OPEN, TRASHED, RESURRECTING, GONE }
29-
30- final AtomicReference<State> state = new AtomicReference<State>(State.OPEN);
31-
32- volatile long maxIdleTime;
33-
34- PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) {
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-}
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +5 −9
@@ -111,7 +111,7 @@
111111 if (currentPool == null || currentPool.isClosed())
112112 return false;
113113
114- PooledConnection connection = null;
114+ Connection connection = null;
115115 try {
116116 connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS);
117117 if (current != null) {
@@ -157,8 +157,7 @@
157157 while (true) {
158158 QueryState previous = queryStateRef.get();
159159 if (previous.isCancelled()) {
160- if (connection instanceof PooledConnection)
161- ((PooledConnection)connection).release();
160+ connection.release();
162161 return;
163162 }
164163 if (previous.inProgress || queryStateRef.compareAndSet(previous, previous.startNext()))
@@ -472,8 +471,7 @@
472471 exceptionToReport = e;
473472 setFinalException(connection, e);
474473 } finally {
475- if (releaseConnection && connection instanceof PooledConnection)
476- ((PooledConnection)connection).release();
474+ connection.release();
477475 if (queriedHost != null && statement != Statement.DEFAULT)
478476 manager.cluster.manager.reportLatency(queriedHost, statement, exceptionToReport, latency);
479477 }
@@ -502,8 +500,7 @@
502500 return;
503501 }
504502
505- if (connection instanceof PooledConnection)
506- ((PooledConnection)connection).release();
503+ connection.release();
507504
508505 // TODO should we check the response ?
509506 switch (response.type) {
@@ -562,8 +559,7 @@
562559
563560 Host queriedHost = current;
564561 try {
565- if (connection instanceof PooledConnection)
566- ((PooledConnection)connection).release();
562+ connection.release();
567563
568564 if (exception instanceof ConnectionException) {
569565 if (metricsEnabled())
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +10 −10
@@ -77,7 +77,7 @@
7777 List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size());
7878 for (Host host : hosts)
7979 if (host.state != Host.State.DOWN)
80- futures.add(maybeAddPool(host));
80+ futures.add(maybeAddPool(host, null));
8181 try {
8282 Futures.successfulAsList(futures).get();
8383 } catch (ExecutionException e) {
@@ -192,7 +192,7 @@
192192 }
193193
194194 // Returns whether there was problem creating the pool
195- ListenableFuture<Boolean> forceRenewPool(final Host host) {
195+ ListenableFuture<Boolean> forceRenewPool(final Host host, Connection reusedConnection) {
196196 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
197197 if (distance == HostDistance.IGNORED)
198198 return Futures.immediateFuture(true);
@@ -201,7 +201,7 @@
201201 return Futures.immediateFuture(false);
202202
203203 final HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this);
204- ListenableFuture<Void> poolInitFuture = newPool.initAsync();
204+ ListenableFuture<Void> poolInitFuture = newPool.initAsync(reusedConnection);
205205
206206 final SettableFuture<Boolean> future = SettableFuture.create();
207207
@@ -239,7 +239,7 @@
239239
240240 // Replace pool for a given host only if it's the given previous value (which can be null)
241241 // This returns a future if the replacement was successful, or null if we raced.
242- private ListenableFuture<Void> replacePool(final Host host, HostDistance distance, HostConnectionPool previous) {
242+ private ListenableFuture<Void> replacePool(final Host host, HostDistance distance, HostConnectionPool previous, Connection reusedConnection) {
243243 if (isClosing)
244244 return MoreFutures.VOID_SUCCESS;
245245
@@ -258,7 +258,7 @@
258258 }
259259 }
260260
261- ListenableFuture<Void> poolInitFuture = newPool.initAsync();
261+ ListenableFuture<Void> poolInitFuture = newPool.initAsync(reusedConnection);
262262
263263 Futures.addCallback(poolInitFuture, new FutureCallback<Void>() {
264264 @Override
@@ -279,7 +279,7 @@
279279 }
280280
281281 // Returns whether there was problem creating the pool
282- ListenableFuture<Boolean> maybeAddPool(final Host host) {
282+ ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection) {
283283 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
284284 if (distance == HostDistance.IGNORED)
285285 return Futures.immediateFuture(true);
@@ -294,7 +294,7 @@
294294 return Futures.immediateFuture(true);
295295
296296 final SettableFuture<Boolean> future = SettableFuture.create();
297- ListenableFuture<Void> newPoolInit = replacePool(host, distance, previous);
297+ ListenableFuture<Void> newPoolInit = replacePool(host, distance, previous, reusedConnection);
298298 if (newPoolInit != null) {
299299 Futures.addCallback(newPoolInit, new FutureCallback<Void>() {
300300 @Override
@@ -358,7 +358,7 @@
358358
359359 if (pool == null) {
360360 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
361- poolCreationFutures.add(maybeAddPool(h));
361+ poolCreationFutures.add(maybeAddPool(h, null));
362362 } else if (dist != pool.hostDistance) {
363363 if (dist == HostDistance.IGNORED) {
364364 toRemove.add(h);
@@ -397,7 +397,7 @@
397397 if (pool == null) {
398398 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
399399 try {
400- maybeAddPool(h).get();
400+ maybeAddPool(h, null).get();
401401 } catch (ExecutionException e) {
402402 // Ignore, maybeAddPool has already handled the error
403403 }
@@ -540,7 +540,7 @@
540540
541541 // Let's not wait too long if we can't get a connection. Things
542542 // will fix themselves once the user tries a query anyway.
543- PooledConnection c = null;
543+ Connection c = null;
544544 boolean timedOut = false;
545545 try {
546546 c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS);
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +14 −14
@@ -56,10 +56,10 @@
5656 HostConnectionPool pool = createPool(2, 2);
5757
5858 assertThat(pool.connections.size()).isEqualTo(2);
59- List<PooledConnection> coreConnections = Lists.newArrayList(pool.connections);
59+ List<Connection> coreConnections = Lists.newArrayList(pool.connections);
6060
6161 for (int i = 0; i < 256; i++) {
62- PooledConnection connection = pool.borrowConnection(100, MILLISECONDS);
62+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
6363 assertThat(coreConnections).contains(connection);
6464 }
6565
@@ -85,17 +85,17 @@
8585 HostConnectionPool pool = createPool(1, 2);
8686
8787 assertThat(pool.connections.size()).isEqualTo(1);
88- List<PooledConnection> coreConnections = Lists.newArrayList(pool.connections);
88+ List<Connection> coreConnections = Lists.newArrayList(pool.connections);
8989
9090 //
9191 for (int i = 0; i < 128; i++) {
92- PooledConnection connection = pool.borrowConnection(100, MILLISECONDS);
92+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
9393 assertThat(coreConnections).contains(connection);
9494 }
9595
9696 // Borrow more and ensure the connection returned is a non-core connection.
9797 for (int i = 0; i < 128; i++) {
98- PooledConnection connection = pool.borrowConnection(100, MILLISECONDS);
98+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
9999 assertThat(coreConnections).doesNotContain(connection);
100100 }
101101
@@ -121,7 +121,7 @@
121121 .setIdleTimeoutSeconds(20);
122122
123123 HostConnectionPool pool = createPool(1, 2);
124- PooledConnection core = pool.connections.get(0);
124+ Connection core = pool.connections.get(0);
125125
126126 // Fill core connection
127127 for (int i = 0; i < 128; i++)
@@ -148,14 +148,14 @@
148148 .setIdleTimeoutSeconds(20);
149149
150150 HostConnectionPool pool = createPool(1, 2);
151- PooledConnection connection1 = pool.connections.get(0);
151+ Connection connection1 = pool.connections.get(0);
152152
153153 for (int i = 0; i < 101; i++)
154154 assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
155155
156156 TimeUnit.MILLISECONDS.sleep(100);
157157 assertThat(pool.connections).hasSize(2);
158- PooledConnection connection2 = pool.connections.get(1);
158+ Connection connection2 = pool.connections.get(1);
159159
160160 assertThat(connection1.inFlight.get()).isEqualTo(101);
161161 assertThat(connection2.inFlight.get()).isEqualTo(0);
@@ -205,14 +205,14 @@
205205 .setIdleTimeoutSeconds(20);
206206
207207 HostConnectionPool pool = createPool(1, 2);
208- PooledConnection connection1 = pool.connections.get(0);
208+ Connection connection1 = pool.connections.get(0);
209209
210210 for (int i = 0; i < 101; i++)
211211 assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
212212
213213 TimeUnit.MILLISECONDS.sleep(100);
214214 assertThat(pool.connections).hasSize(2);
215- PooledConnection connection2 = pool.connections.get(1);
215+ Connection connection2 = pool.connections.get(1);
216216
217217 assertThat(connection1.inFlight.get()).isEqualTo(101);
218218 assertThat(connection2.inFlight.get()).isEqualTo(0);
@@ -247,7 +247,7 @@
247247 TimeUnit.MILLISECONDS.sleep(100);
248248
249249 // Borrow again to get the new connection
250- PooledConnection connection3 = pool.borrowConnection(100, MILLISECONDS);
250+ Connection connection3 = pool.borrowConnection(100, MILLISECONDS);
251251 assertThat(connection3)
252252 .isNotEqualTo(connection2) // should not be the full connection
253253 .isNotEqualTo(connection1); // should not be the previously trashed one
@@ -267,7 +267,7 @@
267267 .setIdleTimeoutSeconds(20);
268268
269269 HostConnectionPool pool = createPool(1, 2);
270- PooledConnection connection1 = pool.connections.get(0);
270+ Connection connection1 = pool.connections.get(0);
271271
272272 // Fill core connection enough to trigger creation of another one
273273 for (int i = 0; i < 110; i++)
@@ -314,7 +314,7 @@
314314 public void should_trash_on_returning_connection_with_insufficient_streams()
315315 throws ConnectionException, TimeoutException, InterruptedException {
316316 HostConnectionPool pool = createPool(1, 2);
317- PooledConnection core = pool.connections.get(0);
317+ Connection core = pool.connections.get(0);
318318
319319 for (int i = 0; i < 128; i++)
320320 assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core);
@@ -323,7 +323,7 @@
323323 assertThat(pool.connections).hasSize(2);
324324
325325 // Grab the new non-core connection and replace it with a spy.
326- PooledConnection extra1 = spy(pool.connections.get(1));
326+ Connection extra1 = spy(pool.connections.get(1));
327327 pool.connections.set(1, extra1);
328328
329329 // Borrow 10 times to ensure pool is utilized.
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +65 −2
@@ -33,6 +33,10 @@
3333 import org.testng.annotations.Test;
3434
3535 import static org.assertj.core.api.Assertions.assertThat;
36+import static org.mockito.Mockito.reset;
37+import static org.mockito.Mockito.spy;
38+import static org.mockito.Mockito.times;
39+import static org.mockito.Mockito.verify;
3640
3741 import com.datastax.driver.core.Host.State;
3842 import com.datastax.driver.core.policies.*;
@@ -141,7 +145,7 @@
141145 CCMBridge ccm = null;
142146 Cluster cluster = null;
143147
144- long reconnectionDelayMillis = 1 * 1000;
148+ long reconnectionDelayMillis = 1000;
145149 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis));
146150
147151 try {
@@ -182,7 +186,7 @@
182186 CCMBridge ccm = null;
183187 Cluster cluster = null;
184188
185- long reconnectionDelayMillis = 1 * 1000;
189+ long reconnectionDelayMillis = 1000;
186190 TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
187191
188192 try {
@@ -220,6 +224,7 @@
220224 // down for the driver.
221225 ccm.start(1);
222226 ccm.waitForUp(1);
227+ assertThat(cluster).host(1).hasState(State.DOWN);
223228
224229 TimeUnit.SECONDS.sleep(Cluster.NEW_NODE_DELAY_SECONDS);
225230 assertThat(cluster).host(1).hasState(State.DOWN);
@@ -236,6 +241,64 @@
236241 }
237242 }
238243
244+ /**
245+ * The connection established by a successful reconnection attempt should be reused in one of the
246+ * connection pools (JAVA-505).
247+ */
248+ @Test(groups = "long")
249+ public void should_use_connection_from_reconnection_in_pool() {
250+ CCMBridge ccm = null;
251+ Cluster cluster = null;
252+
253+ TogglabePolicy loadBalancingPolicy = new TogglabePolicy(new RoundRobinPolicy());
254+
255+ // Spy SocketOptions.getKeepAlive to count how many connections were instantiated.
256+ SocketOptions socketOptions = spy(new SocketOptions());
257+
258+ try {
259+ ccm = CCMBridge.create("test", 1);
260+ cluster = Cluster.builder()
261+ .addContactPoint(CCMBridge.ipOfNode(1))
262+ .withReconnectionPolicy(new ConstantReconnectionPolicy(5000))
263+ .withLoadBalancingPolicy(loadBalancingPolicy)
264+ .withSocketOptions(socketOptions)
265+ .build();
266+ // Create two sessions to have multiple pools
267+ cluster.connect();
268+ cluster.connect();
269+
270+ // Right after init, 1 connection has been opened by the control connection, and 2 (core size) for each pool.
271+ verify(socketOptions, times(5)).getKeepAlive();
272+
273+ // Tweak the LBP so that the control connection never reconnects. This makes it easier
274+ // to reason about the number of connection attempts.
275+ loadBalancingPolicy.returnEmptyQueryPlan = true;
276+
277+ // Stop the node and cancel the reconnection attempts to it
278+ ccm.stop(1);
279+ ccm.waitForDown(1);
280+ assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
281+ Host host1 = TestUtils.findHost(cluster, 1);
282+ host1.getReconnectionAttemptFuture().cancel(false);
283+
284+ ccm.start(1);
285+ ccm.waitForUp(1);
286+
287+ // Reset the spy and count the number of connections attempts for 1 reconnect
288+ reset(socketOptions);
289+ host1.tryReconnectOnce();
290+ assertThat(cluster).host(1).comesUpWithin(120, SECONDS);
291+ // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4
292+ // but the one from the reconnection attempt gets reused).
293+ verify(socketOptions, times(4)).getKeepAlive();
294+ } finally {
295+ if (cluster != null)
296+ cluster.close();
297+ if (ccm != null)
298+ ccm.remove();
299+ }
300+ }
301+
239302 /**
240303 * An authentication provider that allows changing the credentials at runtime, and tracks how many times they have been requested.
241304 */
modified driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +2 −2
@@ -72,7 +72,7 @@
7272 }
7373 }
7474
75- PooledConnection connection = getSingleConnection(session);
75+ Connection connection = getSingleConnection(session);
7676 assertThat(connection.inFlight.get()).isEqualTo(0);
7777 } finally {
7878 if (cluster != null)
@@ -81,7 +81,7 @@
8181 }
8282 }
8383
84- private PooledConnection getSingleConnection(Session session) {
84+ private Connection getSingleConnection(Session session) {
8585 HostConnectionPool pool = ((SessionManager)session).pools.values().iterator().next();
8686 return pool.connections.get(0);
8787 }