Elffuss BraidHub

kikocis/java-driver public

Add TimeoutStressTest for exercising Pool timeout and replace logic.
Changeset0a8f5175c6b187dcb472aac935a839077710fea64f18c26ff19a3a0d542d05d1
AuthorAndrew Tolbert <andrew.tolbert@datastax.com> · 2015-04-10 17:01 -05:00
Committerolim7t <omichallat+github@gmail.com> · 2015-04-17 20:19 +02:00
Parents894f0a0ca7a5

Browse the files at this changeset

5 files changed

modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +2 −1
@@ -2297,7 +2297,8 @@
22972297 private static final int INTERVAL_MS = 15000;
22982298
22992299 private final ScheduledExecutorService executor;
2300- private final Map<Connection, Long> connections = new ConcurrentHashMap<Connection, Long>();
2300+ @VisibleForTesting
2301+ final Map<Connection, Long> connections = new ConcurrentHashMap<Connection, Long>();
23012302
23022303 private volatile boolean shutdown;
23032304
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +54 −79
@@ -15,98 +15,73 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import static java.util.concurrent.TimeUnit.SECONDS;
19-
20-import org.mockito.Mockito;
2118 import org.testng.annotations.Test;
2219
23-import com.datastax.driver.core.Host.State;
24-import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
25-import com.datastax.driver.core.policies.LimitingLoadBalancingPolicy;
26-import com.datastax.driver.core.policies.RoundRobinPolicy;
20+import java.util.Collection;
21+import java.util.Collections;
22+import java.util.concurrent.*;
2723
28-import static com.datastax.driver.core.Assertions.assertThat;
24+import static org.assertj.core.api.Assertions.assertThat;
25+import static org.mockito.Matchers.any;
26+import static org.mockito.Mockito.*;
2927
30-public class PoolingOptionsTest {
28+public class PoolingOptionsTest extends CCMBridge.PerClassSingleNodeCluster {
29+ @Override
30+ protected Collection<String> getTableDefinitions() {
31+ return Collections.emptyList();
32+ }
3133
3234 /**
33- * Tests {@link PoolingOptions#refreshConnectedHost(Host)} through a custom load balancing policy.
35+ * <p>
36+ * Validates that if a custom executor is provided via {@link PoolingOptions#setInitializationExecutor} that it
37+ * is used to create and tear down connections.
38+ * </p>
39+ *
40+ * @test_category connection:connection_pool
41+ * @expected_result executor is used and successfully able to connect and tear down connections.
42+ * @jira_ticket JAVA-692
43+ * @since 2.0.10, 2.1.6
3444 */
35- @Test(groups = "long")
36- public void should_refresh_single_connected_host() {
37- CCMBridge ccm = null;
38- Cluster cluster = null;
45+ @Test(groups = "short")
46+ public void should_be_able_to_use_custom_initialization_executor() {
47+ ThreadPoolExecutor executor = spy(new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
48+ new LinkedBlockingQueue<Runnable>()));
49+
50+ PoolingOptions poolingOptions = new PoolingOptions();
51+ poolingOptions.setInitializationExecutor(executor);
52+
53+ Cluster cluster = Cluster.builder()
54+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
55+ .withPoolingOptions(poolingOptions).build();
3956 try {
40- // This will make the driver use at most 2 hosts, the others will be ignored
41- LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1);
42-
43- // Setup a 3-host cluster, start only two hosts so that we know in advance which ones the policy will use
44- ccm = CCMBridge.create("test");
45- ccm.populate(3);
46- ccm.start(1);
47- ccm.start(2);
48- ccm.waitForUp(1);
49- ccm.waitForUp(2);
50-
51- PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions());
52- cluster = Cluster.builder()
53- .addContactPoint(CCMBridge.ipOfNode(1))
54- .withPoolingOptions(poolingOptions)
55- .withLoadBalancingPolicy(loadBalancingPolicy)
56- .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
57- .build();
57+ cluster.init();
58+ // Ensure executor used.
59+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
60+
61+ // Reset invocation count.
62+ reset();
5863
5964 Session session = cluster.connect();
6065
61- assertThat(cluster).usesControlHost(1);
62- assertThat(cluster).host(1)
63- .hasState(State.UP)
64- .isAtDistance(HostDistance.LOCAL);
65- // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line
66- // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up
67- assertThat(cluster).host(2)
68- .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
69- .isAtDistance(HostDistance.LOCAL);
70-
71- // Bring host 3 up, its presence should be acknowledged but it should be ignored
72- ccm.start(3);
73- ccm.waitForUp(3);
74-
75- assertThat(cluster).host(1)
76- .hasState(State.UP)
77- .isAtDistance(HostDistance.LOCAL);
78- assertThat(cluster).host(2)
79- .hasState(State.UP)
80- .isAtDistance(HostDistance.LOCAL);
81- assertThat(cluster).host(3)
82- .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
83- .isAtDistance(HostDistance.IGNORED);
84- assertThat(session).hasNoPoolFor(3);
85-
86- // Kill host 2, host 3 should take its place
87- ccm.stop(2);
88- TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster);
89-
90- assertThat(cluster).host(1)
91- .hasState(State.UP)
92- .isAtDistance(HostDistance.LOCAL);
93- assertThat(cluster).host(2)
94- .hasState(State.DOWN);
95- assertThat(cluster).host(3)
96- .hasState(State.UP)
97- .isAtDistance(HostDistance.LOCAL);
98- assertThat(session).hasPoolFor(3);
99-
100- // This is when refreshConnectedHost should have been invoked, it triggers pool creation when
101- // we switch the node from IGNORED to UP:
102- Mockito.verify(poolingOptions)
103- .refreshConnectedHost(TestUtils.findHost(cluster, 3));
66+ // Ensure executor used again to establish core connections.
67+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
68+
69+ // Expect core connections + control connection.
70+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(
71+ TestUtils.numberOfLocalCoreConnections(cluster) + 1);
72+
73+ reset();
74+
75+ session.close();
76+
77+ // Executor should have been used to close connections associated with the session.
78+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
10479
80+ // Only the control connection should remain.
81+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(1);
10582 } finally {
106- if (cluster != null)
107- cluster.close();
108- if (ccm != null)
109- ccm.remove();
83+ cluster.close();
84+ executor.shutdown();
11085 }
11186 }
11287 }
added driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +112 −0
@@ -0,0 +1,112 @@
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 static java.util.concurrent.TimeUnit.SECONDS;
19+
20+import org.mockito.Mockito;
21+import org.testng.annotations.Test;
22+
23+import com.datastax.driver.core.Host.State;
24+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
25+import com.datastax.driver.core.policies.LimitingLoadBalancingPolicy;
26+import com.datastax.driver.core.policies.RoundRobinPolicy;
27+
28+import static com.datastax.driver.core.Assertions.assertThat;
29+
30+public class RefreshConnectedHostTest {
31+
32+ /**
33+ * Tests {@link PoolingOptions#refreshConnectedHost(Host)} through a custom load balancing policy.
34+ */
35+ @Test(groups = "long")
36+ public void should_refresh_single_connected_host() {
37+ CCMBridge ccm = null;
38+ Cluster cluster = null;
39+ try {
40+ // This will make the driver use at most 2 hosts, the others will be ignored
41+ LimitingLoadBalancingPolicy loadBalancingPolicy = new LimitingLoadBalancingPolicy(new RoundRobinPolicy(), 2, 1);
42+
43+ // Setup a 3-host cluster, start only two hosts so that we know in advance which ones the policy will use
44+ ccm = CCMBridge.create("test");
45+ ccm.populate(3);
46+ ccm.start(1);
47+ ccm.start(2);
48+ ccm.waitForUp(1);
49+ ccm.waitForUp(2);
50+
51+ PoolingOptions poolingOptions = Mockito.spy(new PoolingOptions());
52+ cluster = Cluster.builder()
53+ .addContactPoint(CCMBridge.ipOfNode(1))
54+ .withPoolingOptions(poolingOptions)
55+ .withLoadBalancingPolicy(loadBalancingPolicy)
56+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
57+ .build();
58+
59+ Session session = cluster.connect();
60+
61+ assertThat(cluster).usesControlHost(1);
62+ assertThat(cluster).host(1)
63+ .hasState(State.UP)
64+ .isAtDistance(HostDistance.LOCAL);
65+ // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line
66+ // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up
67+ assertThat(cluster).host(2)
68+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
69+ .isAtDistance(HostDistance.LOCAL);
70+
71+ // Bring host 3 up, its presence should be acknowledged but it should be ignored
72+ ccm.start(3);
73+ ccm.waitForUp(3);
74+
75+ assertThat(cluster).host(1)
76+ .hasState(State.UP)
77+ .isAtDistance(HostDistance.LOCAL);
78+ assertThat(cluster).host(2)
79+ .hasState(State.UP)
80+ .isAtDistance(HostDistance.LOCAL);
81+ assertThat(cluster).host(3)
82+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
83+ .isAtDistance(HostDistance.IGNORED);
84+ assertThat(session).hasNoPoolFor(3);
85+
86+ // Kill host 2, host 3 should take its place
87+ ccm.stop(2);
88+ TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster);
89+
90+ assertThat(cluster).host(1)
91+ .hasState(State.UP)
92+ .isAtDistance(HostDistance.LOCAL);
93+ assertThat(cluster).host(2)
94+ .hasState(State.DOWN);
95+ assertThat(cluster).host(3)
96+ .hasState(State.UP)
97+ .isAtDistance(HostDistance.LOCAL);
98+ assertThat(session).hasPoolFor(3);
99+
100+ // This is when refreshConnectedHost should have been invoked, it triggers pool creation when
101+ // we switch the node from IGNORED to UP:
102+ Mockito.verify(poolingOptions)
103+ .refreshConnectedHost(TestUtils.findHost(cluster, 3));
104+
105+ } finally {
106+ if (cluster != null)
107+ cluster.close();
108+ if (ccm != null)
109+ ccm.remove();
110+ }
111+ }
112+}
added driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +279 −0
@@ -0,0 +1,279 @@
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 com.datastax.driver.core.exceptions.NoHostAvailableException;
19+import com.datastax.driver.core.utils.SocketChannelMonitor;
20+import com.google.common.collect.Lists;
21+import com.google.common.util.concurrent.FutureCallback;
22+import com.google.common.util.concurrent.Futures;
23+import com.google.common.util.concurrent.ThreadFactoryBuilder;
24+import com.google.common.util.concurrent.Uninterruptibles;
25+import io.netty.channel.socket.SocketChannel;
26+import org.slf4j.Logger;
27+import org.slf4j.LoggerFactory;
28+import org.testng.annotations.AfterClass;
29+import org.testng.annotations.BeforeClass;
30+import org.testng.annotations.Test;
31+
32+import java.net.InetSocketAddress;
33+import java.util.Collection;
34+import java.util.List;
35+import java.util.concurrent.*;
36+import java.util.concurrent.atomic.AtomicBoolean;
37+import java.util.concurrent.atomic.AtomicInteger;
38+
39+import static org.assertj.core.api.Assertions.assertThat;
40+
41+public class TimeoutStressTest {
42+
43+ static final Logger logger = LoggerFactory.getLogger(TimeoutStressTest.class);
44+
45+ // Maximum number of concurrent queries running at a given time.
46+ static final int CONCURRENT_QUERIES = 25;
47+
48+ // How long the test should run for, may want to consider running for longer periods to time to check for leaks
49+ // that could occur over very tiny timing windows.
50+ static final long DURATION = 60000;
51+
52+ // Configured read timeout - this may need to be tuned to the host system running the test.
53+ static final int READ_TIMEOUT_IN_MS = 50;
54+
55+ // Configured connection timeout - this may need to be tuned to the host system running the test.
56+ static final int CONNECTION_TIMEOUT_IN_MS = 20;
57+
58+ // Keyspace to use.
59+ static final String KEYSPACE = "testks";
60+
61+ static Cluster cluster;
62+
63+ static CCMBridge ccmBridge;
64+
65+ static SocketChannelMonitor channelMonitor;
66+
67+ static AtomicInteger executedQueries = new AtomicInteger(0);
68+
69+ static List<InetSocketAddress> nodes;
70+
71+ static PreparedStatement statement;
72+
73+ @BeforeClass(groups = "long")
74+ public void beforeClass() throws Exception {
75+ ccmBridge = CCMBridge.create("test", 3);
76+ channelMonitor = new SocketChannelMonitor();
77+ nodes = Lists.newArrayList(
78+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
79+ new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042),
80+ new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042)
81+ );
82+
83+ PoolingOptions poolingOptions = new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 8);
84+
85+ cluster = Cluster.builder()
86+ .addContactPointsWithPorts(nodes)
87+ .withPoolingOptions(poolingOptions)
88+ .withNettyOptions(channelMonitor.nettyOptions())
89+ .build();
90+ Session session = cluster.connect();
91+ setupSchema(session);
92+ session.close();
93+ }
94+
95+ @AfterClass(groups = "long")
96+ public void afterClass() {
97+ if(ccmBridge != null) {
98+ ccmBridge.stop();
99+ }
100+ if(channelMonitor != null) {
101+ channelMonitor.stop();
102+ }
103+ if(cluster != null) {
104+ cluster.close();
105+ }
106+ }
107+
108+ /**
109+ * <p>
110+ * Validates that under extreme timeout conditions the driver is able to properly maintain connection pools in
111+ * addition to not leaking connections.
112+ *
113+ * <p>
114+ * Does the following:
115+ * <ol>
116+ * <li>Creates a table and loads 30k rows in a single partition.</li>
117+ * <li>Sets the connection and read timeout {@link SocketOptions} to very low values.</li>
118+ * <li>Spawns workers that concurrently execute queries.</li>
119+ * <li>For some duration, repeatedly measures number of open socket connections and warns if exceeded.</li>
120+ * <li>After a duration, resets {@link SocketOptions} to defaults.</li>
121+ * <li>Wait for 20 seconds for reaper to remove old connections and restore pools.</li>
122+ * <li>Ensure pools are restored.</li>
123+ * <li>Shutdown session and ensure that there remains only 1 open connection.</li>
124+ * </ol>
125+ *
126+ * @test_category connection:connection_pool
127+ * @expected_result no connections leak and all host pools are maintained.
128+ * @jira_ticket JAVA-692
129+ * @since 2.0.10, 2.1.6
130+ */
131+ @Test(groups = "long")
132+ public void host_state_should_be_maintained_with_timeouts() {
133+ // Set very low timeouts.
134+ cluster.getConfiguration().getSocketOptions().setConnectTimeoutMillis(CONNECTION_TIMEOUT_IN_MS);
135+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(READ_TIMEOUT_IN_MS);
136+ Session session = cluster.connect();
137+
138+ int workers = Runtime.getRuntime().availableProcessors();
139+ ExecutorService workerPool = Executors.newFixedThreadPool(workers,
140+ new ThreadFactoryBuilder().setNameFormat("timeout-stress-test-worker-%d").setDaemon(true).build());
141+
142+ AtomicBoolean stopped = new AtomicBoolean(false);
143+
144+ // Ensure that we never exceed MaxConnectionsPerHost * nodes + 1 control connection.
145+ int maxConnections = cluster.getConfiguration()
146+ .getPoolingOptions().getMaxConnectionsPerHost(HostDistance.LOCAL) * nodes.size() + 1;
147+
148+ try {
149+ Semaphore concurrentQueries = new Semaphore(CONCURRENT_QUERIES);
150+ for (int i = 0; i < workers; i++) {
151+ workerPool.submit(new TimeoutStressWorker(session, concurrentQueries, stopped));
152+ }
153+
154+ long startTime = System.currentTimeMillis();
155+ while (System.currentTimeMillis() - startTime < DURATION) {
156+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
157+ channelMonitor.report();
158+ // Some connections that are being closed may have had active requests which are delegated to the
159+ // reaper for cleanup later.
160+ Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes);
161+
162+ // Ensure that we don't exceed maximum connections. Log as warning as there will be a bit of a timing
163+ // factor between retrieving open connections and checking the reaper.
164+ if(openChannels.size() > maxConnections) {
165+ logger.warn("{} of open channels: {} exceeds maximum expected: {}. " +
166+ "This could be because there are connections to be cleaned up in the reaper.",
167+ openChannels.size(), maxConnections, openChannels);
168+ }
169+ }
170+ } finally {
171+ stopped.set(true);
172+
173+ // Reset socket timeouts to allow pool to recover.
174+ cluster.getConfiguration().getSocketOptions()
175+ .setConnectTimeoutMillis(SocketOptions.DEFAULT_CONNECT_TIMEOUT_MILLIS);
176+ cluster.getConfiguration().getSocketOptions()
177+ .setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS);
178+
179+ logger.debug("Sleeping 20 seconds to allow connection reaper to clean up connections " +
180+ "and for the pools to recover.");
181+ Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
182+
183+ Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes);
184+ assertThat(openChannels.size())
185+ .as("Number of open connections does not meet expected: %s", openChannels)
186+ .isEqualTo(maxConnections);
187+
188+ session.close();
189+
190+ openChannels = channelMonitor.openChannels(nodes);
191+ assertThat(openChannels.size())
192+ .as("Number of open connections does not meet expected: %s", openChannels)
193+ .isEqualTo(1);
194+
195+ workerPool.shutdown();
196+ }
197+ }
198+
199+ /**
200+ * Creates the testks schema with a 'record' table and preloads 30k records.
201+ */
202+ private static void setupSchema(Session session) throws InterruptedException, ExecutionException, TimeoutException {
203+ logger.debug("Creating keyspace");
204+ session.execute("create KEYSPACE if not exists " + KEYSPACE +
205+ " WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3}");
206+ session.execute("use " + KEYSPACE);
207+
208+ logger.debug("Creating table");
209+ session.execute("create table if NOT EXISTS record (\n"
210+ + " name text,\n"
211+ + " phone text,\n"
212+ + " value text,\n"
213+ + " PRIMARY KEY (name, phone)\n"
214+ + ");");
215+
216+ int records = 30000;
217+ List<ResultSetFuture> futures = Lists.newArrayListWithExpectedSize(records);
218+
219+ for (int i = 0; i < records; i++) {
220+ if (i % 1000 == 0)
221+ logger.debug("Inserting record {}.", i);
222+ futures.add(session.executeAsync(
223+ "insert into record (name, phone, value) values (?, ?, ?)", "0", Integer.toString(i), "test"));
224+ }
225+
226+ statement = session.prepare("select * from " + KEYSPACE + ".record where name=? limit 1000;");
227+
228+ logger.debug("Completed inserting data. Waiting up to 30 for inserts to complete seconds before proceeding.");
229+ Futures.allAsList(futures).get(30, TimeUnit.SECONDS);
230+ logger.debug("Inserts complete.");
231+ }
232+
233+ public static class TimeoutStressWorker implements Runnable {
234+
235+ private final Semaphore concurrentQueries;
236+ private final AtomicBoolean stopped;
237+ private final Session session;
238+
239+ public TimeoutStressWorker(Session session, Semaphore concurrentQueries, AtomicBoolean stopped) {
240+ this.session = session;
241+ this.concurrentQueries = concurrentQueries;
242+ this.stopped = stopped;
243+ }
244+
245+
246+ @Override
247+ public void run() {
248+
249+ while(!stopped.get()) {
250+ try {
251+ concurrentQueries.acquire();
252+ ResultSetFuture future = session.executeAsync(statement.bind("0"));
253+ Futures.addCallback(future, new FutureCallback<ResultSet>() {
254+
255+ @Override
256+ public void onSuccess(ResultSet result) {
257+ concurrentQueries.release();
258+ if(executedQueries.incrementAndGet() % 1000 == 0)
259+ logger.debug("Successfully executed {}. rows: {}", executedQueries.get(), result.getAvailableWithoutFetching());
260+ }
261+
262+ @Override
263+ public void onFailure(Throwable t) {
264+ concurrentQueries.release();
265+ if(t instanceof NoHostAvailableException) {
266+ //logger.error("NHAE: {}", t.getMessage());
267+ } else {
268+ //logger.error("Exception", t);
269+ }
270+ }
271+ });
272+ } catch(Exception e) {
273+ logger.error("Failure while submitting query.", e);
274+ }
275+ }
276+
277+ }
278+ }
279+}
modified driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java +15 −1
@@ -137,17 +137,31 @@
137137 }
138138 }
139139
140+ private static Comparator<SocketChannel> BY_REMOTE_ADDRESS = new Comparator<SocketChannel>() {
141+ @Override
142+ public int compare(SocketChannel t0, SocketChannel t1) {
143+ // Should not be null as these are filtered previously in matchingChannels.
144+ assert t0 != null && t0.remoteAddress() != null;
145+ assert t1 != null && t1.remoteAddress() != null;;
146+ return t0.remoteAddress().toString().compareTo(t1.remoteAddress().toString());
147+ }
148+ };
149+
140150 /**
141151 * @param addresses The addresses to include.
142152 * @return Open channels matching the given socket addresses.
143153 */
144154 public Collection<SocketChannel> openChannels(final Collection<InetSocketAddress> addresses) {
145- return Lists.newArrayList(matchingChannels(new Predicate<SocketChannel>() {
155+ List<SocketChannel> channels = Lists.newArrayList(matchingChannels(new Predicate<SocketChannel>() {
146156 @Override
147157 public boolean apply(SocketChannel input) {
148158 return input.isOpen() && input.remoteAddress() != null && addresses.contains(input.remoteAddress());
149159 }
150160 }));
161+
162+ Collections.sort(channels, BY_REMOTE_ADDRESS);
163+
164+ return channels;
151165 }
152166
153167 /**