Elffuss BraidHub

kikocis/java-driver public

Use same pool implementation for protocol v2 and v3 (JAVA-738).
Changesete6301299a3efcc1b3656a17e375bd767fe66d2e4b7747dc9b4785876af22cef0
Authorolim7t <omichallat+github@gmail.com> · 2015-06-08 16:11 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-06-27 00:11 +02:00
Parents0a63194870de

Browse the files at this changeset

21 files changed

modified changelog/README.md +2 −0
@@ -16,6 +16,8 @@
1616 - [improvement] Provide a way to map computed fields (JAVA-661)
1717 - [improvement] Ignore missing columns in mapper (JAVA-824)
1818 - [bug] Preserve default timestamp for retries and speculative executions (JAVA-724)
19+- [improvement] Use same pool implementation for protocol v2 and v3
20+ (JAVA-738).
1921
2022 Merged from 2.0 branch:
2123
modified clirr-ignores.xml +6 −0
@@ -23,4 +23,10 @@
2323 <justification>This class was accidentally exposed, it was meant to be package-private</justification>
2424 </difference>
2525
26+ <difference>
27+ <differenceType>1001</differenceType> <!-- decreased visibility -->
28+ <className>com/datastax/driver/core/HostConnectionPool$Phase</className>
29+ <justification>False positive: HostConnectionPool is not exposed to clients</justification>
30+ </difference>
31+
2632 </differences>
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +2 −0
@@ -1333,6 +1333,8 @@
13331333 listener.onDown(host);
13341334 }
13351335
1336+ configuration.getPoolingOptions().setProtocolVersion(protocolVersion());
1337+
13361338 for (Host host : metadata.allHosts()) {
13371339 // If the host is down at this stage, it's a contact point that the control connection failed to reach.
13381340 // Reconnection attempts are already scheduled, and the LBP and listeners have been notified above.
deleted driver-core/src/main/java/com/datastax/driver/core/DynamicConnectionPool.java +0 −602
@@ -1,602 +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-
19-import java.util.*;
20-import java.util.concurrent.*;
21-import java.util.concurrent.atomic.AtomicInteger;
22-import java.util.concurrent.locks.*;
23-
24-import com.google.common.annotations.VisibleForTesting;
25-import com.google.common.collect.Lists;
26-import com.google.common.util.concurrent.*;
27-import org.slf4j.Logger;
28-import org.slf4j.LoggerFactory;
29-
30-import com.datastax.driver.core.exceptions.AuthenticationException;
31-import com.datastax.driver.core.utils.MoreFutures;
32-
33-import static com.datastax.driver.core.Connection.State.*;
34-
35-/**
36- * A connection pool with a varying number of connections.
37- *
38- * This is used with {@link ProtocolVersion#V2} and lower.
39- */
40-class DynamicConnectionPool extends HostConnectionPool {
41-
42- private static final Logger logger = LoggerFactory.getLogger(DynamicConnectionPool.class);
43-
44- private static final int MAX_SIMULTANEOUS_CREATION = 1;
45-
46- // When a request timeout, we may never release its stream ID. So over time, a given connection
47- // may get less an less available streams. When the number of available ones go below the
48- // following threshold, we just replace the connection by a new one.
49- private static final int MIN_AVAILABLE_STREAMS = 96;
50-
51- final List<Connection> connections;
52- private final AtomicInteger open;
53- /** The total number of in-flight requests on all connections of this pool. */
54- final AtomicInteger totalInFlight = new AtomicInteger();
55- /** The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}*/
56- private final AtomicInteger maxTotalInFlight = new AtomicInteger();
57-
58- @VisibleForTesting
59- final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
60-
61- private volatile int waiter = 0;
62- private final Lock waitLock = new ReentrantLock(true);
63- private final Condition hasAvailableConnection = waitLock.newCondition();
64-
65- private final Runnable newConnectionTask;
66-
67- private final AtomicInteger scheduledForCreation = new AtomicInteger();
68-
69- public DynamicConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
70- super(host, hostDistance, manager);
71-
72- this.newConnectionTask = new Runnable() {
73- @Override
74- public void run() {
75- addConnectionIfUnderMaximum();
76- scheduledForCreation.decrementAndGet();
77- }
78- };
79-
80- this.connections = new CopyOnWriteArrayList<Connection>();
81- this.open = new AtomicInteger();
82- }
83-
84- @Override
85- ListenableFuture<Void> initAsync(Connection reusedConnection) {
86- // Create initial core connections
87- int capacity = options().getCoreConnectionsPerHost(hostDistance);
88- final List<Connection> connections = Lists.newArrayListWithCapacity(capacity);
89- final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(capacity);
90- for (int i = 0; i < capacity; i++) {
91- Connection connection;
92- ListenableFuture<Void> connectionFuture;
93- // reuse the existing connection only once
94- if (reusedConnection != null && reusedConnection.setPool(this)) {
95- connection = reusedConnection;
96- connectionFuture = MoreFutures.VOID_SUCCESS;
97- } else {
98- connection = manager.connectionFactory().newConnection(this);
99- connectionFuture = connection.initAsync();
100- }
101- reusedConnection = null;
102- connections.add(connection);
103- connectionFutures.add(connectionFuture);
104- }
105-
106- Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
107-
108- ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures);
109-
110- final SettableFuture<Void> initFuture = SettableFuture.create();
111- Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() {
112- @Override
113- public void onSuccess(List<Void> l) {
114- DynamicConnectionPool.this.connections.addAll(connections);
115- open.set(l.size());
116- if (isClosed()) {
117- initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization"));
118- // we're not sure if closeAsync() saw the connections, so ensure they get closed
119- forceClose(connections);
120- } else {
121- logger.trace("Created connection pool to host {}", host);
122- phase.compareAndSet(Phase.INITIALIZING, Phase.READY);
123- initFuture.set(null);
124- }
125- }
126-
127- @Override
128- public void onFailure(Throwable t) {
129- phase.compareAndSet(Phase.INITIALIZING, Phase.INIT_FAILED);
130- forceClose(connections);
131- initFuture.setException(t);
132- }
133- }, initExecutor);
134- return initFuture;
135- }
136-
137- // Clean up if we got an error at construction time but still created part of the core connections
138- private void forceClose(List<Connection> connections) {
139- for (Connection connection : connections) {
140- connection.closeAsync().force();
141- }
142- }
143-
144- private PoolingOptions options() {
145- return manager.configuration().getPoolingOptions();
146- }
147-
148- @Override
149- public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
150- Phase phase = this.phase.get();
151- if (phase != Phase.READY)
152- // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
153- // That being said, maybe having a specific exception could be cleaner.
154- throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
155-
156- if (connections.isEmpty()) {
157- for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
158- // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to
159- // protect against creating connection in excess of core too quickly
160- scheduledForCreation.incrementAndGet();
161- manager.blockingExecutor().submit(newConnectionTask);
162- }
163- Connection c = waitForConnection(timeout, unit);
164- totalInFlight.incrementAndGet();
165- c.setKeyspace(manager.poolsState.keyspace);
166- return c;
167- }
168-
169- int minInFlight = Integer.MAX_VALUE;
170- Connection leastBusy = null;
171- for (Connection connection : connections) {
172- int inFlight = connection.inFlight.get();
173- if (inFlight < minInFlight) {
174- minInFlight = inFlight;
175- leastBusy = connection;
176- }
177- }
178-
179- if (leastBusy == null) {
180- // We could have raced with a shutdown since the last check
181- if (isClosed())
182- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
183- // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between
184- // the previous check to connections and now. But in that case, the line above will have trigger the creation of
185- // a new connection, so just wait that connection and move on
186- leastBusy = waitForConnection(timeout, unit);
187- } else {
188- while (true) {
189- int inFlight = leastBusy.inFlight.get();
190-
191- if (inFlight >= leastBusy.maxAvailableStreams()) {
192- leastBusy = waitForConnection(timeout, unit);
193- break;
194- }
195-
196- if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
197- break;
198- }
199- }
200-
201- int totalInFlightCount = totalInFlight.incrementAndGet();
202- // update max atomically:
203- while (true) {
204- int oldMax = maxTotalInFlight.get();
205- if (totalInFlightCount <= oldMax || maxTotalInFlight.compareAndSet(oldMax, totalInFlightCount))
206- break;
207- }
208-
209- int connectionCount = open.get() + scheduledForCreation.get();
210- if (connectionCount < options().getMaxConnectionsPerHost(hostDistance)) {
211- // Add a connection if we fill the first n-1 connections and almost fill the last one
212- int currentCapacity = (connectionCount - 1) * StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2
213- + options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance);
214- if (totalInFlightCount > currentCapacity)
215- maybeSpawnNewConnection();
216- }
217-
218- leastBusy.setKeyspace(manager.poolsState.keyspace);
219- return leastBusy;
220- }
221-
222- private void awaitAvailableConnection(long timeout, TimeUnit unit) throws InterruptedException {
223- waitLock.lock();
224- waiter++;
225- try {
226- hasAvailableConnection.await(timeout, unit);
227- } finally {
228- waiter--;
229- waitLock.unlock();
230- }
231- }
232-
233- private void signalAvailableConnection() {
234- // Quick check if it's worth signaling to avoid locking
235- if (waiter == 0)
236- return;
237-
238- waitLock.lock();
239- try {
240- hasAvailableConnection.signal();
241- } finally {
242- waitLock.unlock();
243- }
244- }
245-
246- private void signalAllAvailableConnection() {
247- // Quick check if it's worth signaling to avoid locking
248- if (waiter == 0)
249- return;
250-
251- waitLock.lock();
252- try {
253- hasAvailableConnection.signalAll();
254- } finally {
255- waitLock.unlock();
256- }
257- }
258-
259- private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
260- if (timeout == 0)
261- throw new TimeoutException();
262-
263- long start = System.nanoTime();
264- long remaining = timeout;
265- do {
266- try {
267- awaitAvailableConnection(remaining, unit);
268- } catch (InterruptedException e) {
269- Thread.currentThread().interrupt();
270- // If we're interrupted fine, check if there is a connection available but stop waiting otherwise
271- timeout = 0; // this will make us stop the loop if we don't get a connection right away
272- }
273-
274- if (isClosed())
275- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
276-
277- int minInFlight = Integer.MAX_VALUE;
278- Connection leastBusy = null;
279- for (Connection connection : connections) {
280- int inFlight = connection.inFlight.get();
281- if (inFlight < minInFlight) {
282- minInFlight = inFlight;
283- leastBusy = connection;
284- }
285- }
286-
287- // If we race with shutdown, leastBusy could be null. In that case we just loop and we'll throw on the next
288- // iteration anyway
289- if (leastBusy != null) {
290- while (true) {
291- int inFlight = leastBusy.inFlight.get();
292-
293- if (inFlight >= leastBusy.maxAvailableStreams())
294- break;
295-
296- if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
297- return leastBusy;
298- }
299- }
300-
301- remaining = timeout - Cluster.timeSince(start, unit);
302- } while (remaining > 0);
303-
304- throw new TimeoutException();
305- }
306-
307- @Override
308- public void returnConnection(Connection connection) {
309- connection.inFlight.decrementAndGet();
310- totalInFlight.decrementAndGet();
311-
312- if (isClosed()) {
313- close(connection);
314- return;
315- }
316-
317- if (connection.isDefunct()) {
318- // As part of making it defunct, we have already replaced it or
319- // closed the pool.
320- return;
321- }
322-
323- if (connection.state.get() != TRASHED) {
324- if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) {
325- replaceConnection(connection);
326- } else {
327- signalAvailableConnection();
328- }
329- }
330- }
331-
332- // Trash the connection and create a new one, but we don't call trashConnection
333- // directly because we want to make sure the connection is always trashed.
334- private void replaceConnection(Connection connection) {
335- if (!connection.state.compareAndSet(OPEN, TRASHED))
336- return;
337- open.decrementAndGet();
338- maybeSpawnNewConnection();
339- connection.maxIdleTime = Long.MIN_VALUE;
340- doTrashConnection(connection);
341- }
342-
343- private boolean trashConnection(Connection connection) {
344- if (!connection.state.compareAndSet(OPEN, TRASHED))
345- return true;
346-
347- // First, make sure we don't go below core connections
348- for (;;) {
349- int opened = open.get();
350- if (opened <= options().getCoreConnectionsPerHost(hostDistance)) {
351- connection.state.set(OPEN);
352- return false;
353- }
354-
355- if (open.compareAndSet(opened, opened - 1))
356- break;
357- }
358- logger.trace("Trashing {}", connection);
359- connection.maxIdleTime = System.currentTimeMillis() + options().getIdleTimeoutSeconds() * 1000;
360- doTrashConnection(connection);
361- return true;
362- }
363-
364- private void doTrashConnection(Connection connection) {
365- connections.remove(connection);
366- trash.add(connection);
367- }
368-
369- private boolean addConnectionIfUnderMaximum() {
370-
371- // First, make sure we don't cross the allowed limit of open connections
372- for(;;) {
373- int opened = open.get();
374- if (opened >= options().getMaxConnectionsPerHost(hostDistance))
375- return false;
376-
377- if (open.compareAndSet(opened, opened + 1))
378- break;
379- }
380-
381- if (phase.get() != Phase.READY) {
382- open.decrementAndGet();
383- return false;
384- }
385-
386- // Now really open the connection
387- try {
388- Connection newConnection = tryResurrectFromTrash();
389- if (newConnection == null) {
390- logger.debug("Creating new connection on busy pool to {}", host);
391- newConnection = manager.connectionFactory().open(this);
392- }
393- connections.add(newConnection);
394-
395- newConnection.state.compareAndSet(RESURRECTING, OPEN); // no-op if it was already OPEN
396-
397- // We might have raced with pool shutdown since the last check; ensure the connection gets closed in case the pool did not do it.
398- if (isClosed() && !newConnection.isClosed()) {
399- close(newConnection);
400- open.decrementAndGet();
401- return false;
402- }
403-
404- signalAvailableConnection();
405- return true;
406- } catch (InterruptedException e) {
407- Thread.currentThread().interrupt();
408- // Skip the open but ignore otherwise
409- open.decrementAndGet();
410- return false;
411- } catch (ConnectionException e) {
412- open.decrementAndGet();
413- logger.debug("Connection error to {} while creating additional connection", host);
414- return false;
415- } catch (AuthenticationException e) {
416- // This shouldn't really happen in theory
417- open.decrementAndGet();
418- logger.error("Authentication error while creating additional connection (error is: {})", e.getMessage());
419- return false;
420- } catch (UnsupportedProtocolVersionException e) {
421- // This shouldn't happen since we shouldn't have been able to connect in the first place
422- open.decrementAndGet();
423- logger.error("UnsupportedProtocolVersionException error while creating additional connection (error is: {})", e.getMessage());
424- return false;
425- } catch (ClusterNameMismatchException e) {
426- open.decrementAndGet();
427- logger.error("ClusterNameMismatchException error while creating additional connection (error is: {})", e.getMessage());
428- return false;
429- }
430- }
431-
432- private Connection tryResurrectFromTrash() {
433- long highestMaxIdleTime = System.currentTimeMillis();
434- Connection chosen = null;
435-
436- while (true) {
437- for (Connection connection : trash)
438- if (connection.maxIdleTime > highestMaxIdleTime && connection.maxAvailableStreams() > MIN_AVAILABLE_STREAMS) {
439- chosen = connection;
440- highestMaxIdleTime = connection.maxIdleTime;
441- }
442-
443- if (chosen == null)
444- return null;
445- else if (chosen.state.compareAndSet(TRASHED, RESURRECTING))
446- break;
447- }
448- logger.trace("Resurrecting {}", chosen);
449- trash.remove(chosen);
450- return chosen;
451- }
452-
453- private void maybeSpawnNewConnection() {
454- while (true) {
455- int inCreation = scheduledForCreation.get();
456- if (inCreation >= MAX_SIMULTANEOUS_CREATION)
457- return;
458- if (scheduledForCreation.compareAndSet(inCreation, inCreation + 1))
459- break;
460- }
461-
462- manager.blockingExecutor().submit(newConnectionTask);
463- }
464-
465- @Override
466- void replaceDefunctConnection(final Connection connection) {
467- if (connection.state.compareAndSet(OPEN, GONE))
468- open.decrementAndGet();
469- if (connections.remove(connection))
470- manager.blockingExecutor().submit(new Runnable() {
471- @Override
472- public void run() {
473- addConnectionIfUnderMaximum();
474- }
475- });
476- }
477-
478- @Override
479- void cleanupIdleConnections(long now) {
480- if (isClosed())
481- return;
482-
483- shrinkIfBelowCapacity();
484- cleanupTrash(now);
485- }
486-
487- /** If we have more active connections than needed, trash some of them */
488- private void shrinkIfBelowCapacity() {
489- int currentLoad = maxTotalInFlight.getAndSet(totalInFlight.get());
490-
491- int needed = currentLoad / StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2 + 1;
492- if (currentLoad % StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2 > options().getMaxSimultaneousRequestsPerConnectionThreshold(hostDistance))
493- needed += 1;
494- needed = Math.max(needed, options().getCoreConnectionsPerHost(hostDistance));
495- int actual = open.get();
496- int toTrash = Math.max(0, actual - needed);
497-
498- logger.trace("Current inFlight = {}, {} connections needed, {} connections available, trashing {}",
499- currentLoad, needed, actual, toTrash);
500-
501- if (toTrash <= 0)
502- return;
503-
504- for (Connection connection : connections)
505- if (trashConnection(connection)) {
506- toTrash -= 1;
507- if (toTrash == 0)
508- return;
509- }
510- }
511-
512- /** Close connections that have been sitting in the trash for too long */
513- private void cleanupTrash(long now) {
514- for (Connection connection : trash) {
515- if (connection.maxIdleTime < now && connection.state.compareAndSet(TRASHED, GONE)) {
516- if (connection.inFlight.get() == 0) {
517- logger.trace("Cleaning up {}", connection);
518- trash.remove(connection);
519- close(connection);
520- } else {
521- // Given that idleTimeout >> request timeout, all outstanding requests should
522- // have finished by now, so we should not get here.
523- // Restore the status so that it's retried on the next cleanup.
524- connection.state.set(TRASHED);
525- }
526- }
527- }
528- }
529-
530- private void close(final Connection connection) {
531- connection.closeAsync();
532- }
533-
534- protected CloseFuture makeCloseFuture() {
535- // Wake up all threads that wait
536- signalAllAvailableConnection();
537-
538- return new CloseFuture.Forwarding(discardAvailableConnections());
539- }
540-
541- private List<CloseFuture> discardAvailableConnections() {
542- // Note: if this gets called before initialization has completed, both connections and trash will be empty,
543- // so this will return an empty list
544-
545- List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size());
546-
547- for (final Connection connection : connections) {
548- CloseFuture future = connection.closeAsync();
549- future.addListener(new Runnable() {
550- public void run() {
551- if (connection.state.compareAndSet(OPEN, GONE))
552- open.decrementAndGet();
553- }
554- }, MoreExecutors.sameThreadExecutor());
555- futures.add(future);
556- }
557-
558- // Some connections in the trash might still be open if they hadn't reached their idle timeout
559- for (Connection connection : trash)
560- futures.add(connection.closeAsync());
561-
562- return futures;
563- }
564-
565- // This creates connections if we have less than core connections (if we
566- // have more than core, connection will just get trash when we can).
567- @Override
568- public void ensureCoreConnections() {
569- if (isClosed())
570- return;
571-
572- // Note: this process is a bit racy, but it doesn't matter since we're still guaranteed to not create
573- // more connection than maximum (and if we create more than core connection due to a race but this isn't
574- // justified by the load, the connection in excess will be quickly trashed anyway)
575- int opened = open.get();
576- for (int i = opened; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
577- // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to
578- // protect against creating connection in excess of core too quickly
579- scheduledForCreation.incrementAndGet();
580- manager.blockingExecutor().submit(newConnectionTask);
581- }
582- }
583-
584- @Override
585- public int opened() {
586- return open.get();
587- }
588-
589- @Override
590- int trashed() {
591- return trash.size();
592- }
593-
594- @Override
595- public int inFlightQueriesCount() {
596- int count = 0;
597- for (Connection connection : connections) {
598- count += connection.inFlight.get();
599- }
600- return count;
601- }
602-}
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +554 −34
@@ -15,45 +15,86 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.TimeUnit;
19-import java.util.concurrent.TimeoutException;
18+import java.util.ArrayList;
19+import java.util.List;
20+import java.util.Set;
21+import java.util.concurrent.*;
22+import java.util.concurrent.atomic.AtomicInteger;
2023 import java.util.concurrent.atomic.AtomicReference;
24+import java.util.concurrent.locks.Condition;
25+import java.util.concurrent.locks.Lock;
26+import java.util.concurrent.locks.ReentrantLock;
2127
22-import com.google.common.util.concurrent.ListenableFuture;
28+import com.google.common.annotations.VisibleForTesting;
29+import com.google.common.collect.Lists;
30+import com.google.common.util.concurrent.*;
31+import org.slf4j.Logger;
32+import org.slf4j.LoggerFactory;
2333
24-/**
25- * A set of connections to a live host.
26- *
27- * We use different strategies depending of the protocol version in use.
28- */
29-abstract class HostConnectionPool {
34+import com.datastax.driver.core.exceptions.AuthenticationException;
35+import com.datastax.driver.core.utils.MoreFutures;
3036
31- static HostConnectionPool newInstance(Host host, HostDistance hostDistance, SessionManager manager, ProtocolVersion version) {
32- switch (version) {
33- case V1:
34- case V2:
35- return new DynamicConnectionPool(host, hostDistance, manager);
36- case V3:
37- return new SingleConnectionPool(host, hostDistance, manager);
38- default:
39- throw version.unsupported();
40- }
41- }
37+import static com.datastax.driver.core.Connection.State.GONE;
38+import static com.datastax.driver.core.Connection.State.OPEN;
39+import static com.datastax.driver.core.Connection.State.RESURRECTING;
40+import static com.datastax.driver.core.Connection.State.TRASHED;
41+
42+class HostConnectionPool {
43+
44+ private static final Logger logger = LoggerFactory.getLogger(HostConnectionPool.class);
45+
46+ private static final int MAX_SIMULTANEOUS_CREATION = 1;
4247
4348 final Host host;
4449 volatile HostDistance hostDistance;
4550 protected final SessionManager manager;
4651
52+ final List<Connection> connections;
53+ private final AtomicInteger open;
54+ /** The total number of in-flight requests on all connections of this pool. */
55+ final AtomicInteger totalInFlight = new AtomicInteger();
56+ /** The maximum value of {@link #totalInFlight} since the last call to {@link #cleanupIdleConnections(long)}*/
57+ private final AtomicInteger maxTotalInFlight = new AtomicInteger();
58+ @VisibleForTesting
59+ final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
60+
61+ private volatile int waiter = 0;
62+ private final Lock waitLock = new ReentrantLock(true);
63+ private final Condition hasAvailableConnection = waitLock.newCondition();
64+
65+ private final Runnable newConnectionTask;
66+
67+ private final AtomicInteger scheduledForCreation = new AtomicInteger();
68+
4769 protected final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
4870
49- protected enum Phase { INITIALIZING, READY, INIT_FAILED, CLOSING }
71+ private enum Phase {INITIALIZING, READY, INIT_FAILED, CLOSING}
72+
5073 protected final AtomicReference<Phase> phase = new AtomicReference<Phase>(Phase.INITIALIZING);
5174
52- protected HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
75+ // When a request times out, we may never release its stream ID. So over time, a given connection
76+ // may get less an less available streams. When the number of available ones go below the
77+ // following threshold, we just replace the connection by a new one.
78+ private final int minAllowedStreams;
79+
80+ public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
5381 assert hostDistance != HostDistance.IGNORED;
5482 this.host = host;
5583 this.hostDistance = hostDistance;
5684 this.manager = manager;
85+
86+ this.newConnectionTask = new Runnable() {
87+ @Override
88+ public void run() {
89+ addConnectionIfUnderMaximum();
90+ scheduledForCreation.decrementAndGet();
91+ }
92+ };
93+
94+ this.connections = new CopyOnWriteArrayList<Connection>();
95+ this.open = new AtomicInteger();
96+
97+ this.minAllowedStreams = options().getMaxRequestsPerConnection(hostDistance) * 3 / 4;
5798 }
5899
59100 /**
@@ -61,25 +102,451 @@
61102 * reuse as part of this pool. Might be null or already used by another
62103 * pool.
63104 */
64- abstract ListenableFuture<Void> initAsync(Connection reusedConnection);
105+ ListenableFuture<Void> initAsync(Connection reusedConnection) {
106+ // Create initial core connections
107+ int capacity = options().getCoreConnectionsPerHost(hostDistance);
108+ final List<Connection> connections = Lists.newArrayListWithCapacity(capacity);
109+ final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(capacity);
110+ for (int i = 0; i < capacity; i++) {
111+ Connection connection;
112+ ListenableFuture<Void> connectionFuture;
113+ // reuse the existing connection only once
114+ if (reusedConnection != null && reusedConnection.setPool(this)) {
115+ connection = reusedConnection;
116+ connectionFuture = MoreFutures.VOID_SUCCESS;
117+ } else {
118+ connection = manager.connectionFactory().newConnection(this);
119+ connectionFuture = connection.initAsync();
120+ }
121+ reusedConnection = null;
122+ connections.add(connection);
123+ connectionFutures.add(connectionFuture);
124+ }
125+
126+ Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
127+
128+ ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures);
129+
130+ final SettableFuture<Void> initFuture = SettableFuture.create();
131+ Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() {
132+ @Override
133+ public void onSuccess(List<Void> l) {
134+ HostConnectionPool.this.connections.addAll(connections);
135+ open.set(l.size());
136+ if (isClosed()) {
137+ initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization"));
138+ // we're not sure if closeAsync() saw the connections, so ensure they get closed
139+ forceClose(connections);
140+ } else {
141+ logger.trace("Created connection pool to host {}", host);
142+ phase.compareAndSet(Phase.INITIALIZING, Phase.READY);
143+ initFuture.set(null);
144+ }
145+ }
146+
147+ @Override
148+ public void onFailure(Throwable t) {
149+ phase.compareAndSet(Phase.INITIALIZING, Phase.INIT_FAILED);
150+ forceClose(connections);
151+ initFuture.setException(t);
152+ }
153+ }, initExecutor);
154+ return initFuture;
155+ }
156+
157+ // Clean up if we got an error at construction time but still created part of the core connections
158+ private void forceClose(List<Connection> connections) {
159+ for (Connection connection : connections) {
160+ connection.closeAsync().force();
161+ }
162+ }
163+
164+ private PoolingOptions options() {
165+ return manager.configuration().getPoolingOptions();
166+ }
167+
168+ public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
169+ Phase phase = this.phase.get();
170+ if (phase != Phase.READY)
171+ // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
172+ // That being said, maybe having a specific exception could be cleaner.
173+ throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
174+
175+ if (connections.isEmpty()) {
176+ for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
177+ // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to
178+ // protect against creating connection in excess of core too quickly
179+ scheduledForCreation.incrementAndGet();
180+ manager.blockingExecutor().submit(newConnectionTask);
181+ }
182+ Connection c = waitForConnection(timeout, unit);
183+ totalInFlight.incrementAndGet();
184+ c.setKeyspace(manager.poolsState.keyspace);
185+ return c;
186+ }
187+
188+ int minInFlight = Integer.MAX_VALUE;
189+ Connection leastBusy = null;
190+ for (Connection connection : connections) {
191+ int inFlight = connection.inFlight.get();
192+ if (inFlight < minInFlight) {
193+ minInFlight = inFlight;
194+ leastBusy = connection;
195+ }
196+ }
197+
198+ if (leastBusy == null) {
199+ // We could have raced with a shutdown since the last check
200+ if (isClosed())
201+ throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
202+ // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between
203+ // the previous check to connections and now. But in that case, the line above will have trigger the creation of
204+ // a new connection, so just wait that connection and move on
205+ leastBusy = waitForConnection(timeout, unit);
206+ } else {
207+ while (true) {
208+ int inFlight = leastBusy.inFlight.get();
209+
210+ if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) {
211+ leastBusy = waitForConnection(timeout, unit);
212+ break;
213+ }
214+
215+ if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
216+ break;
217+ }
218+ }
219+
220+ int totalInFlightCount = totalInFlight.incrementAndGet();
221+ // update max atomically:
222+ while (true) {
223+ int oldMax = maxTotalInFlight.get();
224+ if (totalInFlightCount <= oldMax || maxTotalInFlight.compareAndSet(oldMax, totalInFlightCount))
225+ break;
226+ }
227+
228+ int connectionCount = open.get() + scheduledForCreation.get();
229+ if (connectionCount < options().getMaxConnectionsPerHost(hostDistance)) {
230+ // Add a connection if we fill the first n-1 connections and almost fill the last one
231+ int currentCapacity = (connectionCount - 1) * options().getMaxRequestsPerConnection(hostDistance)
232+ + options().getNewConnectionThreshold(hostDistance);
233+ if (totalInFlightCount > currentCapacity)
234+ maybeSpawnNewConnection();
235+ }
236+
237+ leastBusy.setKeyspace(manager.poolsState.keyspace);
238+ return leastBusy;
239+ }
240+
241+ private void awaitAvailableConnection(long timeout, TimeUnit unit) throws InterruptedException {
242+ waitLock.lock();
243+ waiter++;
244+ try {
245+ hasAvailableConnection.await(timeout, unit);
246+ } finally {
247+ waiter--;
248+ waitLock.unlock();
249+ }
250+ }
251+
252+ private void signalAvailableConnection() {
253+ // Quick check if it's worth signaling to avoid locking
254+ if (waiter == 0)
255+ return;
256+
257+ waitLock.lock();
258+ try {
259+ hasAvailableConnection.signal();
260+ } finally {
261+ waitLock.unlock();
262+ }
263+ }
264+
265+ private void signalAllAvailableConnection() {
266+ // Quick check if it's worth signaling to avoid locking
267+ if (waiter == 0)
268+ return;
269+
270+ waitLock.lock();
271+ try {
272+ hasAvailableConnection.signalAll();
273+ } finally {
274+ waitLock.unlock();
275+ }
276+ }
277+
278+ private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
279+ if (timeout == 0)
280+ throw new TimeoutException();
281+
282+ long start = System.nanoTime();
283+ long remaining = timeout;
284+ do {
285+ try {
286+ awaitAvailableConnection(remaining, unit);
287+ } catch (InterruptedException e) {
288+ Thread.currentThread().interrupt();
289+ // If we're interrupted fine, check if there is a connection available but stop waiting otherwise
290+ timeout = 0; // this will make us stop the loop if we don't get a connection right away
291+ }
292+
293+ if (isClosed())
294+ throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
295+
296+ int minInFlight = Integer.MAX_VALUE;
297+ Connection leastBusy = null;
298+ for (Connection connection : connections) {
299+ int inFlight = connection.inFlight.get();
300+ if (inFlight < minInFlight) {
301+ minInFlight = inFlight;
302+ leastBusy = connection;
303+ }
304+ }
305+
306+ // If we race with shutdown, leastBusy could be null. In that case we just loop and we'll throw on the next
307+ // iteration anyway
308+ if (leastBusy != null) {
309+ while (true) {
310+ int inFlight = leastBusy.inFlight.get();
311+
312+ if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance)))
313+ break;
314+
315+ if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1))
316+ return leastBusy;
317+ }
318+ }
319+
320+ remaining = timeout - Cluster.timeSince(start, unit);
321+ } while (remaining > 0);
322+
323+ throw new TimeoutException();
324+ }
65325
66- abstract Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException;
326+ public void returnConnection(Connection connection) {
327+ connection.inFlight.decrementAndGet();
328+ totalInFlight.decrementAndGet();
67329
68- abstract void returnConnection(Connection connection);
330+ if (isClosed()) {
331+ close(connection);
332+ return;
333+ }
334+
335+ if (connection.isDefunct()) {
336+ // As part of making it defunct, we have already replaced it or
337+ // closed the pool.
338+ return;
339+ }
340+
341+ if (connection.state.get() != TRASHED) {
342+ if (connection.maxAvailableStreams() < minAllowedStreams) {
343+ replaceConnection(connection);
344+ } else {
345+ signalAvailableConnection();
346+ }
347+ }
348+ }
349+
350+ // Trash the connection and create a new one, but we don't call trashConnection
351+ // directly because we want to make sure the connection is always trashed.
352+ private void replaceConnection(Connection connection) {
353+ if (!connection.state.compareAndSet(OPEN, TRASHED))
354+ return;
355+ open.decrementAndGet();
356+ maybeSpawnNewConnection();
357+ connection.maxIdleTime = Long.MIN_VALUE;
358+ doTrashConnection(connection);
359+ }
360+
361+ private boolean trashConnection(Connection connection) {
362+ if (!connection.state.compareAndSet(OPEN, TRASHED))
363+ return true;
364+
365+ // First, make sure we don't go below core connections
366+ for (; ; ) {
367+ int opened = open.get();
368+ if (opened <= options().getCoreConnectionsPerHost(hostDistance)) {
369+ connection.state.set(OPEN);
370+ return false;
371+ }
372+
373+ if (open.compareAndSet(opened, opened - 1))
374+ break;
375+ }
376+ logger.trace("Trashing {}", connection);
377+ connection.maxIdleTime = System.currentTimeMillis() + options().getIdleTimeoutSeconds() * 1000;
378+ doTrashConnection(connection);
379+ return true;
380+ }
381+
382+ private void doTrashConnection(Connection connection) {
383+ connections.remove(connection);
384+ trash.add(connection);
385+ }
386+
387+ private boolean addConnectionIfUnderMaximum() {
388+
389+ // First, make sure we don't cross the allowed limit of open connections
390+ for (; ; ) {
391+ int opened = open.get();
392+ if (opened >= options().getMaxConnectionsPerHost(hostDistance))
393+ return false;
394+
395+ if (open.compareAndSet(opened, opened + 1))
396+ break;
397+ }
398+
399+ if (phase.get() != Phase.READY) {
400+ open.decrementAndGet();
401+ return false;
402+ }
403+
404+ // Now really open the connection
405+ try {
406+ Connection newConnection = tryResurrectFromTrash();
407+ if (newConnection == null) {
408+ logger.debug("Creating new connection on busy pool to {}", host);
409+ newConnection = manager.connectionFactory().open(this);
410+ }
411+ connections.add(newConnection);
412+
413+ newConnection.state.compareAndSet(RESURRECTING, OPEN); // no-op if it was already OPEN
414+
415+ // We might have raced with pool shutdown since the last check; ensure the connection gets closed in case the pool did not do it.
416+ if (isClosed() && !newConnection.isClosed()) {
417+ close(newConnection);
418+ open.decrementAndGet();
419+ return false;
420+ }
421+
422+ signalAvailableConnection();
423+ return true;
424+ } catch (InterruptedException e) {
425+ Thread.currentThread().interrupt();
426+ // Skip the open but ignore otherwise
427+ open.decrementAndGet();
428+ return false;
429+ } catch (ConnectionException e) {
430+ open.decrementAndGet();
431+ logger.debug("Connection error to {} while creating additional connection", host);
432+ return false;
433+ } catch (AuthenticationException e) {
434+ // This shouldn't really happen in theory
435+ open.decrementAndGet();
436+ logger.error("Authentication error while creating additional connection (error is: {})", e.getMessage());
437+ return false;
438+ } catch (UnsupportedProtocolVersionException e) {
439+ // This shouldn't happen since we shouldn't have been able to connect in the first place
440+ open.decrementAndGet();
441+ logger.error("UnsupportedProtocolVersionException error while creating additional connection (error is: {})", e.getMessage());
442+ return false;
443+ } catch (ClusterNameMismatchException e) {
444+ open.decrementAndGet();
445+ logger.error("ClusterNameMismatchException error while creating additional connection (error is: {})", e.getMessage());
446+ return false;
447+ }
448+ }
449+
450+ private Connection tryResurrectFromTrash() {
451+ long highestMaxIdleTime = System.currentTimeMillis();
452+ Connection chosen = null;
453+
454+ while (true) {
455+ for (Connection connection : trash)
456+ if (connection.maxIdleTime > highestMaxIdleTime && connection.maxAvailableStreams() > minAllowedStreams) {
457+ chosen = connection;
458+ highestMaxIdleTime = connection.maxIdleTime;
459+ }
460+
461+ if (chosen == null)
462+ return null;
463+ else if (chosen.state.compareAndSet(TRASHED, RESURRECTING))
464+ break;
465+ }
466+ logger.trace("Resurrecting {}", chosen);
467+ trash.remove(chosen);
468+ return chosen;
469+ }
470+
471+ private void maybeSpawnNewConnection() {
472+ while (true) {
473+ int inCreation = scheduledForCreation.get();
474+ if (inCreation >= MAX_SIMULTANEOUS_CREATION)
475+ return;
476+ if (scheduledForCreation.compareAndSet(inCreation, inCreation + 1))
477+ break;
478+ }
479+
480+ manager.blockingExecutor().submit(newConnectionTask);
481+ }
482+
483+ void replaceDefunctConnection(final Connection connection) {
484+ if (connection.state.compareAndSet(OPEN, GONE))
485+ open.decrementAndGet();
486+ if (connections.remove(connection))
487+ manager.blockingExecutor().submit(new Runnable() {
488+ @Override
489+ public void run() {
490+ addConnectionIfUnderMaximum();
491+ }
492+ });
493+ }
494+
495+ void cleanupIdleConnections(long now) {
496+ if (isClosed())
497+ return;
498+
499+ shrinkIfBelowCapacity();
500+ cleanupTrash(now);
501+ }
69502
70- abstract void ensureCoreConnections();
503+ /** If we have more active connections than needed, trash some of them */
504+ private void shrinkIfBelowCapacity() {
505+ int currentLoad = maxTotalInFlight.getAndSet(totalInFlight.get());
71506
72- abstract void replaceDefunctConnection(final Connection connection);
507+ int maxRequestsPerConnection = options().getMaxRequestsPerConnection(hostDistance);
508+ int needed = currentLoad / maxRequestsPerConnection + 1;
509+ if (currentLoad % maxRequestsPerConnection > options().getNewConnectionThreshold(hostDistance))
510+ needed += 1;
511+ needed = Math.max(needed, options().getCoreConnectionsPerHost(hostDistance));
512+ int actual = open.get();
513+ int toTrash = Math.max(0, actual - needed);
73514
74- abstract void cleanupIdleConnections(long now);
515+ logger.trace("Current inFlight = {}, {} connections needed, {} connections available, trashing {}",
516+ currentLoad, needed, actual, toTrash);
75517
76- abstract int opened();
518+ if (toTrash <= 0)
519+ return;
77520
78- abstract int trashed();
521+ for (Connection connection : connections)
522+ if (trashConnection(connection)) {
523+ toTrash -= 1;
524+ if (toTrash == 0)
525+ return;
526+ }
527+ }
79528
80- abstract int inFlightQueriesCount();
529+ /** Close connections that have been sitting in the trash for too long */
530+ private void cleanupTrash(long now) {
531+ for (Connection connection : trash) {
532+ if (connection.maxIdleTime < now && connection.state.compareAndSet(TRASHED, GONE)) {
533+ if (connection.inFlight.get() == 0) {
534+ logger.trace("Cleaning up {}", connection);
535+ trash.remove(connection);
536+ close(connection);
537+ } else {
538+ // Given that idleTimeout >> request timeout, all outstanding requests should
539+ // have finished by now, so we should not get here.
540+ // Restore the status so that it's retried on the next cleanup.
541+ connection.state.set(TRASHED);
542+ }
543+ }
544+ }
545+ }
81546
82- protected abstract CloseFuture makeCloseFuture();
547+ private void close(final Connection connection) {
548+ connection.closeAsync();
549+ }
83550
84551 public final boolean isClosed() {
85552 return closeFuture.get() != null;
@@ -93,13 +560,66 @@
93560
94561 phase.set(Phase.CLOSING);
95562
96- future = makeCloseFuture();
563+ // Wake up all threads that wait
564+ signalAllAvailableConnection();
565+
566+ future = new CloseFuture.Forwarding(discardAvailableConnections());
97567
98568 return closeFuture.compareAndSet(null, future)
99569 ? future
100570 : closeFuture.get(); // We raced, it's ok, return the future that was actually set
101571 }
102572
573+ public int opened() {
574+ return open.get();
575+ }
576+
577+ int trashed() {
578+ return trash.size();
579+ }
580+
581+ private List<CloseFuture> discardAvailableConnections() {
582+ // Note: if this gets called before initialization has completed, both connections and trash will be empty,
583+ // so this will return an empty list
584+
585+ List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size());
586+
587+ for (final Connection connection : connections) {
588+ CloseFuture future = connection.closeAsync();
589+ future.addListener(new Runnable() {
590+ public void run() {
591+ if (connection.state.compareAndSet(OPEN, GONE))
592+ open.decrementAndGet();
593+ }
594+ }, MoreExecutors.sameThreadExecutor());
595+ futures.add(future);
596+ }
597+
598+ // Some connections in the trash might still be open if they hadn't reached their idle timeout
599+ for (Connection connection : trash)
600+ futures.add(connection.closeAsync());
601+
602+ return futures;
603+ }
604+
605+ // This creates connections if we have less than core connections (if we
606+ // have more than core, connection will just get trash when we can).
607+ public void ensureCoreConnections() {
608+ if (isClosed())
609+ return;
610+
611+ // Note: this process is a bit racy, but it doesn't matter since we're still guaranteed to not create
612+ // more connection than maximum (and if we create more than core connection due to a race but this isn't
613+ // justified by the load, the connection in excess will be quickly trashed anyway)
614+ int opened = open.get();
615+ for (int i = opened; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
616+ // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to
617+ // protect against creating connection in excess of core too quickly
618+ scheduledForCreation.incrementAndGet();
619+ manager.blockingExecutor().submit(newConnectionTask);
620+ }
621+ }
622+
103623 static class PoolState {
104624 volatile String keyspace;
105625
@@ -107,4 +627,4 @@
107627 this.keyspace = keyspace;
108628 }
109629 }
110-}
No newline at the end of the file
630+}
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +281 −203
@@ -15,51 +15,66 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.util.Map;
1819 import java.util.concurrent.Executor;
1920
2021 import com.google.common.base.Preconditions;
22+import com.google.common.collect.ImmutableMap;
2123 import com.google.common.util.concurrent.MoreExecutors;
2224
25+import static com.datastax.driver.core.HostDistance.LOCAL;
26+import static com.datastax.driver.core.HostDistance.REMOTE;
27+
2328 /**
2429 * Options related to connection pooling.
2530 * <p>
26- * The driver uses connections in an asynchronous manner. Meaning that
31+ * The driver uses connections in an asynchronous manner, meaning that
2732 * multiple requests can be submitted on the same connection at the same
28- * time. This means that the driver only needs to maintain a relatively
29- * small number of connections to each Cassandra host. These options allow
30- * the driver to control how many connections are kept exactly.
33+ * time. Therefore only a relatively small number of connections is needed.
34+ * For each host, the driver uses a connection pool that may have a variable
35+ * size (it will automatically adjust to the current load).
3136 * <p>
32- * <b>With {@code ProtocolVersion#V2} or below:</b>
33- * for each host, the driver keeps a core pool of connections open at all
34- * times determined by calling ({@link #getCoreConnectionsPerHost}).
35- * If the use of those connections reaches a configurable threshold
36- * ({@link #getMaxSimultaneousRequestsPerConnectionThreshold}),
37- * more connections are created up to the configurable maximum number of
38- * connections ({@link #getMaxConnectionsPerHost}). When the pool exceeds
39- * the maximum number of connections, connections in excess are
40- * reclaimed.
37+ * With {@code ProtocolVersion#V2} or below, there are at most 128 simultaneous
38+ * requests per connection, so the pool defaults to a variable size. You will
39+ * typically raise the maximum capacity by adding more connections with
40+ * {@link #setMaxRequestsPerConnection(HostDistance, int)}.
4141 * <p>
42- * <b>With {@code ProtocolVersion#V3} or above:</b>
43- * the driver uses a single connection for each {@code LOCAL} or {@code REMOTE}
44- * host. This connection can handle a larger amount of simultaneous requests,
45- * limited by {@link #getMaxSimultaneousRequestsPerHostThreshold(HostDistance)}.
42+ * With {@code ProtocolVersion#V3} or above, there are up to 32768 requests per
43+ * connection, and the pool defaults to a fixed size of 1. You will typically
44+ * raise the maximum capacity by allowing more simultaneous requests per connection
45+ * ({@link #setMaxRequestsPerConnection(HostDistance, int)}).
4646 * <p>
47- * Each of these parameters can be separately set for {@code LOCAL} and
47+ * All parameters can be separately set for {@code LOCAL} and
4848 * {@code REMOTE} hosts ({@link HostDistance}). For {@code IGNORED} hosts,
49- * the default for all those settings is 0 and cannot be changed.
49+ * no connections are created so these settings cannot be changed.
5050 */
5151 public class PoolingOptions {
5252
53- private static final int DEFAULT_MAX_REQUESTS_PER_CONNECTION = 100;
54-
55- private static final int DEFAULT_CORE_POOL_LOCAL = 2;
56- private static final int DEFAULT_CORE_POOL_REMOTE = 1;
57-
58- private static final int DEFAULT_MAX_POOL_LOCAL = 8;
59- private static final int DEFAULT_MAX_POOL_REMOTE = 2;
60-
61- private static final int DEFAULT_MAX_REQUESTS_PER_HOST_LOCAL = 1024;
62- private static final int DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE = 256;
53+ static final int UNSET = Integer.MIN_VALUE;
54+
55+ private static final Map<ProtocolVersion, Map<String, Integer>> DEFAULTS = ImmutableMap.<ProtocolVersion, Map<String, Integer>>of(
56+ ProtocolVersion.V2, ImmutableMap.<String, Integer>builder()
57+ .put("corePoolLocal", 2)
58+ .put("maxPoolLocal", 8)
59+ .put("corePoolRemote", 1)
60+ .put("maxPoolRemote", 2)
61+ .put("newConnectionThresholdLocal", 100)
62+ .put("newConnectionThresholdRemote", 100)
63+ .put("maxRequestsPerConnectionLocal", 128)
64+ .put("maxRequestsPerConnectionRemote", 128)
65+ .build(),
66+
67+ ProtocolVersion.V3, ImmutableMap.<String, Integer>builder()
68+ .put("corePoolLocal", 1)
69+ .put("maxPoolLocal", 1)
70+ .put("corePoolRemote", 1)
71+ .put("maxPoolRemote", 1)
72+ .put("newConnectionThresholdLocal", 800)
73+ .put("newConnectionThresholdRemote", 200)
74+ .put("maxRequestsPerConnectionLocal", 1024)
75+ .put("maxRequestsPerConnectionRemote", 256)
76+ .build()
77+ );
6378
6479 private static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120;
6580 private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
@@ -68,126 +83,31 @@
6883 private static final Executor DEFAULT_INITIALIZATION_EXECUTOR = MoreExecutors.sameThreadExecutor();
6984
7085 private volatile Cluster.Manager manager;
86+ private volatile ProtocolVersion protocolVersion;
87+
88+ // The defaults for these fields depend on the protocol version, which is only known after control connection initialization.
89+ // Yet if the user set them before initialization, we want to keep their values. So we use -1 to mean "uninitialized".
90+ private final int[] coreConnections = new int[]{ UNSET, UNSET, 0 };
91+ private final int[] maxConnections = new int[]{ UNSET, UNSET, 0 };
92+ private final int[] newConnectionThreshold = new int[]{ UNSET, UNSET, 0 };
93+ private volatile int maxRequestsPerConnectionLocal = UNSET;
94+ private volatile int maxRequestsPerConnectionRemote = UNSET;
7195
72- private final int[] maxSimultaneousRequestsPerConnection = new int[]{ DEFAULT_MAX_REQUESTS_PER_CONNECTION, DEFAULT_MAX_REQUESTS_PER_CONNECTION, 0 };
73-
74- private final int[] coreConnections = new int[] { DEFAULT_CORE_POOL_LOCAL, DEFAULT_CORE_POOL_REMOTE, 0 };
75- private final int[] maxConnections = new int[] { DEFAULT_MAX_POOL_LOCAL , DEFAULT_MAX_POOL_REMOTE, 0 };
76-
77- private volatile int maxSimultaneousRequestsPerHostLocal = DEFAULT_MAX_REQUESTS_PER_HOST_LOCAL;
78- private volatile int maxSimultaneousRequestsPerHostRemote = DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE;
79-
8096 private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS;
8197 private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
8298 private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
8399
84100 private volatile Executor initializationExecutor = DEFAULT_INITIALIZATION_EXECUTOR;
85101
86- public PoolingOptions() {}
102+ public PoolingOptions() {
103+ }
87104
88105 void register(Cluster.Manager manager) {
89106 this.manager = manager;
90107 }
91108
92- /**
93- * Returns the number of simultaneous requests on a connection below which
94- * connections in excess are reclaimed.
95- * <p>
96- * This option is only used with {@code ProtocolVersion#V2} or below.
97- * <p>
98- * If an opened connection to an host at distance {@code distance}
99- * handles less than this number of simultaneous requests and there is
100- * more than {@link #getCoreConnectionsPerHost} connections open to this
101- * host, the connection is closed.
102- * <p>
103- * The default value for this option is 25 for {@code LOCAL} and
104- * {@code REMOTE} hosts.
105- *
106- * @param distance the {@code HostDistance} for which to return this threshold.
107- * @return the configured threshold, or the default one if none have been set.
108- *
109- * @deprecated this option isn't used anymore with the current pool resizing algorithm.
110- */
111- @Deprecated
112- public int getMinSimultaneousRequestsPerConnectionThreshold(HostDistance distance) {
113- return 0;
114- }
115-
116- /**
117- * Sets the number of simultaneous requests on a connection below which
118- * connections in excess are reclaimed.
119- * <p>
120- * This option is only used with {@code ProtocolVersion#V2} or below.
121- *
122- * @param distance the {@code HostDistance} for which to configure this threshold.
123- * @param newMinSimultaneousRequests the value to set (between 0 and 128).
124- * @return this {@code PoolingOptions}.
125- *
126- * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED}, or if {@code minSimultaneousRequests}
127- * is not in range, or if {@code newMinSimultaneousRequests} is greater than the maximum value for this distance.
128- *
129- * @deprecated this option isn't used anymore with the current pool resizing algorithm.
130- */
131- @Deprecated
132- public synchronized PoolingOptions setMinSimultaneousRequestsPerConnectionThreshold(HostDistance distance, int newMinSimultaneousRequests) {
133- return this;
134- }
135-
136- /**
137- * Returns the number of simultaneous requests on all connections to an host after
138- * which more connections are created.
139- * <p>
140- * This option is only used with {@code ProtocolVersion#V2} or below.
141- * <p>
142- * If all the connections opened to an host at distance {@code
143- * distance} connection are handling more than this number of
144- * simultaneous requests and there is less than
145- * {@link #getMaxConnectionsPerHost} connections open to this host, a
146- * new connection is open.
147- * <p>
148- * Note that a given connection cannot handle more than 128
149- * simultaneous requests (protocol limitation).
150- * <p>
151- * The default value for this option is 100 for {@code LOCAL} and
152- * {@code REMOTE} hosts.
153- *
154- * @param distance the {@code HostDistance} for which to return this threshold.
155- * @return the configured threshold, or the default one if none have been set.
156- */
157- public int getMaxSimultaneousRequestsPerConnectionThreshold(HostDistance distance) {
158- return maxSimultaneousRequestsPerConnection[distance.ordinal()];
159- }
160-
161- /**
162- * Sets number of simultaneous requests on all connections to an host after
163- * which more connections are created.
164- * <p>
165- * This option is only used with {@code ProtocolVersion#V2} or below.
166- *
167- * @param distance the {@code HostDistance} for which to configure this threshold.
168- * @param newMaxSimultaneousRequests the value to set (between 0 and 128).
169- * @return this {@code PoolingOptions}.
170- *
171- * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED}, or if {@code maxSimultaneousRequests}
172- * is not in range, or if {@code newMaxSimultaneousRequests} is less than the minimum value for this distance.
173- */
174- public synchronized PoolingOptions setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance distance, int newMaxSimultaneousRequests) {
175- if (distance == HostDistance.IGNORED)
176- throw new IllegalArgumentException("Cannot set max simultaneous requests per connection threshold for " + distance + " hosts");
177-
178- checkRequestsPerConnectionRange(newMaxSimultaneousRequests, "Max simultaneous requests per connection", distance);
179- maxSimultaneousRequestsPerConnection[distance.ordinal()] = newMaxSimultaneousRequests;
180- return this;
181- }
182-
183109 /**
184110 * Returns the core number of connections per host.
185- * <p>
186- * This option is only used with {@code ProtocolVersion#V2} or below.
187- * <p>
188- * For the provided {@code distance}, this correspond to the number of
189- * connections initially created and kept open to each host of that
190- * distance.
191111 *
192112 * @param distance the {@code HostDistance} for which to return this threshold.
193113 * @return the core number of connections per host at distance {@code distance}.
@@ -199,7 +119,15 @@
199119 /**
200120 * Sets the core number of connections per host.
201121 * <p>
202- * This option is only used with {@code ProtocolVersion#V2} or below.
122+ * For the provided {@code distance}, this corresponds to the number of
123+ * connections initially created and kept open to each host of that
124+ * distance.
125+ * <p>
126+ * The default value is:
127+ * <ul>
128+ * <li>with {@code ProtocolVersion#V2} or below: 2 for {@code LOCAL} hosts and 1 for {@code REMOTE} hosts.</li>
129+ * <li>with {@code ProtocolVersion#V3} or above: 1 for all hosts.</li>
130+ * </ul>
203131 *
204132 * @param distance the {@code HostDistance} for which to set this threshold.
205133 * @param newCoreConnections the value to set
@@ -210,9 +138,11 @@
210138 */
211139 public synchronized PoolingOptions setCoreConnectionsPerHost(HostDistance distance, int newCoreConnections) {
212140 if (distance == HostDistance.IGNORED)
213- throw new IllegalArgumentException("Cannot set core connections per host for " + distance + " hosts");
141+ throw new IllegalArgumentException("Cannot set core connections per host for " + distance + " hosts");
142+
143+ if (maxConnections[distance.ordinal()] != UNSET)
144+ checkConnectionsPerHostOrder(newCoreConnections, maxConnections[distance.ordinal()], distance);
214145
215- checkConnectionsPerHostOrder(newCoreConnections, maxConnections[distance.ordinal()], distance);
216146 int oldCore = coreConnections[distance.ordinal()];
217147 coreConnections[distance.ordinal()] = newCoreConnections;
218148 if (oldCore < newCoreConnections && manager != null)
@@ -222,11 +152,6 @@
222152
223153 /**
224154 * Returns the maximum number of connections per host.
225- * <p>
226- * This option is only used with {@code ProtocolVersion#V2} or below.
227- * <p>
228- * For the provided {@code distance}, this correspond to the maximum
229- * number of connections that can be created per host at that distance.
230155 *
231156 * @param distance the {@code HostDistance} for which to return this threshold.
232157 * @return the maximum number of connections per host at distance {@code distance}.
@@ -238,7 +163,14 @@
238163 /**
239164 * Sets the maximum number of connections per host.
240165 * <p>
241- * This option is only used with {@code ProtocolVersion#V2} or below.
166+ * For the provided {@code distance}, this corresponds to the maximum
167+ * number of connections that can be created per host at that distance.
168+ * <p>
169+ * The default value is:
170+ * <ul>
171+ * <li>with {@code ProtocolVersion#V2} or below: 8 for {@code LOCAL} hosts and 2 for {@code REMOTE} hosts.</li>
172+ * <li>with {@code ProtocolVersion#V3} or above: 1 for all hosts.</li>
173+ * </ul>
242174 *
243175 * @param distance the {@code HostDistance} for which to set this threshold.
244176 * @param newMaxConnections the value to set
@@ -251,7 +183,9 @@
251183 if (distance == HostDistance.IGNORED)
252184 throw new IllegalArgumentException("Cannot set max connections per host for " + distance + " hosts");
253185
254- checkConnectionsPerHostOrder(coreConnections[distance.ordinal()], newMaxConnections, distance);
186+ if (coreConnections[distance.ordinal()] != UNSET)
187+ checkConnectionsPerHostOrder(coreConnections[distance.ordinal()], newMaxConnections, distance);
188+
255189 maxConnections[distance.ordinal()] = newMaxConnections;
256190 return this;
257191 }
@@ -280,6 +214,109 @@
280214 return this;
281215 }
282216
217+ /**
218+ * Returns the threshold that triggers the creation of a new connection to a host.
219+ *
220+ * @param distance the {@code HostDistance} for which to return this threshold.
221+ * @return the configured threshold, or the default one if none have been set.
222+ *
223+ * @see #setNewConnectionThreshold(HostDistance, int)
224+ */
225+ public int getNewConnectionThreshold(HostDistance distance) {
226+ return newConnectionThreshold[distance.ordinal()];
227+ }
228+
229+ /**
230+ * Sets the threshold that triggers the creation of a new connection to a host.
231+ * <p>
232+ * A new connection gets created if:
233+ * <ul>
234+ * <li>N connections are open</li>
235+ * <li><tt>N < {@link #getMaxConnectionsPerHost(HostDistance)}</tt></li>
236+ * <li>the number of active requests is more than
237+ * <tt>(N - 1) * {@link #getMaxRequestsPerConnection(HostDistance)} + {@link #getNewConnectionThreshold(HostDistance)}</tt>
238+ * </li>
239+ * </ul>
240+ * In other words, if all but the last connection are full, and the last connection is above this threshold.
241+ * <p>
242+ * The default value is:
243+ * <ul>
244+ * <li>with {@code ProtocolVersion#V2} or below: 100 for all hosts.</li>
245+ * <li>with {@code ProtocolVersion#V3} or above: 800 for {@code LOCAL} hosts and 200 for {@code REMOTE} hosts.</li>
246+ * </ul>
247+ *
248+ * @param distance the {@code HostDistance} for which to configure this threshold.
249+ * @param newValue the value to set (between 0 and 128).
250+ * @return this {@code PoolingOptions}.
251+ *
252+ * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED}, or if {@code maxSimultaneousRequests}
253+ * is not in range, or if {@code newValue} is less than the minimum value for this distance.
254+ */
255+ public synchronized PoolingOptions setNewConnectionThreshold(HostDistance distance, int newValue) {
256+ if (distance == HostDistance.IGNORED)
257+ throw new IllegalArgumentException("Cannot set new connection threshold for " + distance + " hosts");
258+
259+ checkRequestsPerConnectionRange(newValue, "New connection threshold", distance);
260+ newConnectionThreshold[distance.ordinal()] = newValue;
261+ return this;
262+ }
263+
264+ /**
265+ * Returns the maximum number of requests per connection.
266+ *
267+ * @param distance the {@code HostDistance} for which to return this threshold.
268+ * @return the maximum number of requests per connection at distance {@code distance}.
269+ *
270+ * @see #setMaxRequestsPerConnection(HostDistance, int)
271+ */
272+ public int getMaxRequestsPerConnection(HostDistance distance) {
273+ switch (distance) {
274+ case LOCAL:
275+ return maxRequestsPerConnectionLocal;
276+ case REMOTE:
277+ return maxRequestsPerConnectionRemote;
278+ default:
279+ return 0;
280+ }
281+ }
282+
283+ /**
284+ * Sets the maximum number of requests per connection.
285+ * <p>
286+ * The default value is:
287+ * <ul>
288+ * <li>with {@code ProtocolVersion#V2} or below: 128 for all hosts (there should not be any reason to change this).</li>
289+ * <li>with {@code ProtocolVersion#V3} or above: 1024 for {@code LOCAL} hosts and 256 for {@code REMOTE} hosts.
290+ * These values were chosen so that the default V2 and V3 configuration generate the same load on a Cassandra cluster.
291+ * Protocol V3 can go much higher (up to 32768), so if your number of clients is low, don't hesitate to experiment with
292+ * higher values. If you have more than one connection per host, consider also adjusting
293+ * {@link #setNewConnectionThreshold(HostDistance, int)}.
294+ * </li>
295+ * </ul>
296+ *
297+ * @param distance the {@code HostDistance} for which to set this threshold.
298+ * @param newMaxRequests the value to set.
299+ * @return this {@code PoolingOptions}.
300+ *
301+ * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
302+ * or if {@code newMaxConnections} is not within the allowed range.
303+ */
304+ public PoolingOptions setMaxRequestsPerConnection(HostDistance distance, int newMaxRequests) {
305+ checkRequestsPerConnectionRange(newMaxRequests, "Max requests per connection", distance);
306+
307+ switch (distance) {
308+ case LOCAL:
309+ maxRequestsPerConnectionLocal = newMaxRequests;
310+ break;
311+ case REMOTE:
312+ maxRequestsPerConnectionRemote = newMaxRequests;
313+ break;
314+ default:
315+ throw new IllegalArgumentException("Cannot set max requests per host for " + distance + " hosts");
316+ }
317+ return this;
318+ }
319+
283320 /**
284321 * Returns the timeout before an idle connection is removed.
285322 *
@@ -322,7 +359,7 @@
322359 * If no connection is available within that time, the driver will try the
323360 * next host from the query plan.
324361 * <p>
325- * If this option is set to zero, the driver won't wait at all.
362+ * The default is 5 seconds. If this option is set to zero, the driver won't wait at all.
326363 *
327364 * @param poolTimeoutMillis the new value in milliseconds.
328365 * @return this {@code PoolingOptions}
@@ -367,58 +404,6 @@
367404 return this;
368405 }
369406
370- /**
371- * Returns the maximum number of requests per host.
372- * <p>
373- * This option is only used with {@code ProtocolVersion#V3} or above.
374- * <p>
375- * The default value for this option is 1024 for {@code LOCAL} and 256 for
376- * {@code REMOTE} hosts.
377- *
378- * @param distance the {@code HostDistance} for which to return this threshold.
379- * @return the maximum number of requests per host at distance {@code distance}.
380- */
381- public int getMaxSimultaneousRequestsPerHostThreshold(HostDistance distance) {
382- switch (distance) {
383- case LOCAL:
384- return maxSimultaneousRequestsPerHostLocal;
385- case REMOTE:
386- return maxSimultaneousRequestsPerHostRemote;
387- default:
388- return 0;
389- }
390- }
391-
392- /**
393- * Sets the maximum number of requests per host.
394- * <p>
395- * This option is only used with {@code ProtocolVersion#V3} or above.
396- *
397- * @param distance the {@code HostDistance} for which to set this threshold.
398- * @param newMaxRequests the value to set (between 1 and 32768).
399- * @return this {@code PoolingOptions}.
400- *
401- * @throws IllegalArgumentException if {@code distance == HostDistance.IGNORED},
402- * or if {@code newMaxConnections} is not within the allowed range.
403- */
404- public PoolingOptions setMaxSimultaneousRequestsPerHostThreshold(HostDistance distance, int newMaxRequests) {
405- if (newMaxRequests <= 0 || newMaxRequests > StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V3)
406- throw new IllegalArgumentException(String.format("Max requests must be in the range (1, %d)",
407- StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V3));
408-
409- switch (distance) {
410- case LOCAL:
411- maxSimultaneousRequestsPerHostLocal = newMaxRequests;
412- break;
413- case REMOTE:
414- maxSimultaneousRequestsPerHostRemote = newMaxRequests;
415- break;
416- default:
417- throw new IllegalArgumentException("Cannot set max requests per host for " + distance + " hosts");
418- }
419- return this;
420- }
421-
422407 /**
423408 * Returns the executor to use for connection initialization.
424409 *
@@ -455,6 +440,43 @@
455440 return this;
456441 }
457442
443+ synchronized void setProtocolVersion(ProtocolVersion protocolVersion) {
444+ this.protocolVersion = protocolVersion;
445+
446+ ProtocolVersion referenceVersion = (protocolVersion.compareTo(ProtocolVersion.V2) <= 0)
447+ ? ProtocolVersion.V2
448+ : ProtocolVersion.V3;
449+ Map<String, Integer> defaults = DEFAULTS.get(referenceVersion);
450+
451+ if (coreConnections[LOCAL.ordinal()] == UNSET)
452+ coreConnections[LOCAL.ordinal()] = defaults.get("corePoolLocal");
453+ if (maxConnections[LOCAL.ordinal()] == UNSET)
454+ maxConnections[LOCAL.ordinal()] = defaults.get("maxPoolLocal");
455+ checkConnectionsPerHostOrder(coreConnections[LOCAL.ordinal()], maxConnections[LOCAL.ordinal()], LOCAL);
456+
457+ if (coreConnections[REMOTE.ordinal()] == UNSET)
458+ coreConnections[REMOTE.ordinal()] = defaults.get("corePoolRemote");
459+ if (maxConnections[REMOTE.ordinal()] == UNSET)
460+ maxConnections[REMOTE.ordinal()] = defaults.get("maxPoolRemote");
461+ checkConnectionsPerHostOrder(coreConnections[REMOTE.ordinal()], maxConnections[REMOTE.ordinal()], REMOTE);
462+
463+ if (newConnectionThreshold[LOCAL.ordinal()] == UNSET)
464+ newConnectionThreshold[LOCAL.ordinal()] = defaults.get("newConnectionThresholdLocal");
465+ checkRequestsPerConnectionRange(newConnectionThreshold[LOCAL.ordinal()], "New connection threshold", LOCAL);
466+
467+ if (newConnectionThreshold[REMOTE.ordinal()] == UNSET)
468+ newConnectionThreshold[REMOTE.ordinal()] = defaults.get("newConnectionThresholdRemote");
469+ checkRequestsPerConnectionRange(newConnectionThreshold[REMOTE.ordinal()], "New connection threshold", REMOTE);
470+
471+ if (maxRequestsPerConnectionLocal == UNSET)
472+ maxRequestsPerConnectionLocal = defaults.get("maxRequestsPerConnectionLocal");
473+ checkRequestsPerConnectionRange(maxRequestsPerConnectionLocal, "Max requests per connection", LOCAL);
474+
475+ if (maxRequestsPerConnectionRemote == UNSET)
476+ maxRequestsPerConnectionRemote = defaults.get("maxRequestsPerConnectionRemote");
477+ checkRequestsPerConnectionRange(maxRequestsPerConnectionRemote, "Max requests per connection", REMOTE);
478+ }
479+
458480 /**
459481 * Requests the driver to re-evaluate the {@link HostDistance} (through the configured
460482 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known
@@ -475,16 +497,72 @@
475497 manager.refreshConnectedHost(host);
476498 }
477499
478- private static void checkRequestsPerConnectionRange(int value, String description, HostDistance distance) {
479- if (value < 0 || value > StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2)
500+ private void checkRequestsPerConnectionRange(int value, String description, HostDistance distance) {
501+ // If we don't know the protocol version yet, use the highest possible upper bound, this will get checked again when possible
502+ int max = (protocolVersion == null || protocolVersion.compareTo(ProtocolVersion.V3) >= 0)
503+ ? StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V3
504+ : StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2;
505+
506+ if (value < 0 || value > max)
480507 throw new IllegalArgumentException(String.format("%s for %s hosts must be in the range (0, %d)",
481- description, distance,
482- StreamIdGenerator.MAX_STREAM_PER_CONNECTION_V2));
508+ description, distance, max));
483509 }
484510
485511 private static void checkConnectionsPerHostOrder(int core, int max, HostDistance distance) {
486512 if (core > max)
487513 throw new IllegalArgumentException(String.format("Core connections for %s hosts must be less than max (%d > %d)",
488- distance, core, max));
514+ distance, core, max));
515+ }
516+
517+ /**
518+ * @deprecated this option isn't used anymore with the current pool resizing algorithm.
519+ */
520+ @Deprecated
521+ public int getMinSimultaneousRequestsPerConnectionThreshold(HostDistance distance) {
522+ return 0;
523+ }
524+
525+ /**
526+ * @deprecated this option isn't used anymore with the current pool resizing algorithm.
527+ */
528+ @Deprecated
529+ public synchronized PoolingOptions setMinSimultaneousRequestsPerConnectionThreshold(HostDistance distance, int newMinSimultaneousRequests) {
530+ return this;
531+ }
532+
533+ /**
534+ * @deprecated this method has been renamed to {@link #getNewConnectionThreshold(HostDistance)}. This method calls the new one internally,
535+ * but you should use the new one in your code.
536+ */
537+ @Deprecated
538+ public int getMaxSimultaneousRequestsPerConnectionThreshold(HostDistance distance) {
539+ return getNewConnectionThreshold(distance);
540+ }
541+
542+ /**
543+ * @deprecated this method has been renamed to {@link #setNewConnectionThreshold(HostDistance, int)}. This method calls the new one
544+ * internally, but you should use the new one in your code.
545+ */
546+ @Deprecated
547+ public PoolingOptions setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance distance, int newMaxSimultaneousRequests) {
548+ return this.setNewConnectionThreshold(distance, newMaxSimultaneousRequests);
549+ }
550+
551+ /**
552+ * @deprecated this method has been renamed to {@link #getMaxRequestsPerConnection(HostDistance)}. This method calls the new one internally,
553+ * but you should use the new one in your code.
554+ */
555+ @Deprecated
556+ public int getMaxSimultaneousRequestsPerHostThreshold(HostDistance distance) {
557+ return this.getMaxRequestsPerConnection(distance);
558+ }
559+
560+ /**
561+ * @deprecated this method has been renamed to {@link #setMaxRequestsPerConnection(HostDistance, int)}. This method calls the new one internally,
562+ * but you should use the new one in your code.
563+ */
564+ @Deprecated
565+ public PoolingOptions setMaxSimultaneousRequestsPerHostThreshold(HostDistance distance, int newMaxRequests) {
566+ return this.setMaxRequestsPerConnection(distance, newMaxRequests);
489567 }
490568 }
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +3 −5
@@ -205,8 +205,7 @@
205205 if (isClosing)
206206 return Futures.immediateFuture(false);
207207
208- final HostConnectionPool newPool = HostConnectionPool.newInstance(host, distance, SessionManager.this,
209- cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum());
208+ final HostConnectionPool newPool = new HostConnectionPool(host, distance, this);
210209 ListenableFuture<Void> poolInitFuture = newPool.initAsync(reusedConnection);
211210
212211 final SettableFuture<Boolean> future = SettableFuture.create();
@@ -248,8 +247,7 @@
248247 if (isClosing)
249248 return MoreFutures.VOID_SUCCESS;
250249
251- final HostConnectionPool newPool = HostConnectionPool.newInstance(host, distance, this,
252- cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum());
250+ final HostConnectionPool newPool = new HostConnectionPool(host, distance, this);
253251 if (previous == null) {
254252 if (pools.putIfAbsent(host, newPool) != null) {
255253 return null;
@@ -628,7 +626,7 @@
628626 }
629627
630628 openConnections[i] = p.opened();
631- inFlightQueries[i] = p.inFlightQueriesCount();
629+ inFlightQueries[i] = p.totalInFlight.get();
632630 trashedConnections[i] = p.trashed();
633631 i++;
634632 }
deleted driver-core/src/main/java/com/datastax/driver/core/SingleConnectionPool.java +0 −407
@@ -1,407 +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-
19-import java.util.ArrayList;
20-import java.util.List;
21-import java.util.Set;
22-import java.util.concurrent.CopyOnWriteArraySet;
23-import java.util.concurrent.Executor;
24-import java.util.concurrent.TimeUnit;
25-import java.util.concurrent.TimeoutException;
26-import java.util.concurrent.atomic.AtomicBoolean;
27-import java.util.concurrent.atomic.AtomicReference;
28-import java.util.concurrent.locks.Condition;
29-import java.util.concurrent.locks.Lock;
30-import java.util.concurrent.locks.ReentrantLock;
31-
32-import com.google.common.util.concurrent.*;
33-import org.slf4j.Logger;
34-import org.slf4j.LoggerFactory;
35-
36-import com.datastax.driver.core.exceptions.AuthenticationException;
37-import com.datastax.driver.core.utils.MoreFutures;
38-
39-import static com.datastax.driver.core.Connection.State.GONE;
40-import static com.datastax.driver.core.Connection.State.OPEN;
41-import static com.datastax.driver.core.Connection.State.TRASHED;
42-
43-/**
44- * A connection pool with a a single connection.
45- *
46- * This is used with {@link ProtocolVersion#V3} and higher.
47- */
48-class SingleConnectionPool extends HostConnectionPool {
49-
50- private static final Logger logger = LoggerFactory.getLogger(SingleConnectionPool.class);
51-
52- // When a request timeout, we may never release its stream ID. So over time, a given connection
53- // may get less an less available streams. When the number of available ones go below the
54- // following threshold, we just replace the connection by a new one.
55- private static final int MIN_AVAILABLE_STREAMS = 32768 * 3 / 4;
56-
57- volatile AtomicReference<Connection> connectionRef = new AtomicReference<Connection>();
58- private final AtomicBoolean open = new AtomicBoolean();
59- private final Set<Connection> trash = new CopyOnWriteArraySet<Connection>();
60-
61- private volatile int waiter = 0;
62- private final Lock waitLock = new ReentrantLock(true);
63- private final Condition hasAvailableConnection = waitLock.newCondition();
64-
65- private final Runnable newConnectionTask;
66-
67- private final AtomicBoolean scheduledForCreation = new AtomicBoolean();
68-
69- public SingleConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) {
70- super(host, hostDistance, manager);
71-
72- this.newConnectionTask = new Runnable() {
73- @Override
74- public void run() {
75- addConnectionIfNeeded();
76- scheduledForCreation.set(false);
77- }
78- };
79- }
80-
81- @Override
82- ListenableFuture<Void> initAsync(Connection reusedConnection) {
83- final Connection connection;
84- ListenableFuture<Void> connectionFuture;
85- if (reusedConnection != null && reusedConnection.setPool(this)) {
86- connection = reusedConnection;
87- connectionFuture = MoreFutures.VOID_SUCCESS;
88- } else {
89- connection = manager.connectionFactory().newConnection(this);
90- connectionFuture = connection.initAsync();
91- }
92-
93- Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
94-
95- final SettableFuture<Void> initFuture = SettableFuture.create();
96- Futures.addCallback(connectionFuture, new FutureCallback<Void>() {
97- @Override
98- public void onSuccess(Void result) {
99- connectionRef.set(connection);
100- open.set(true);
101- if (isClosed()) {
102- initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization"));
103- // we're not sure if closeAsync() saw the connection, so ensure it gets closed
104- connection.closeAsync().force();
105- } else {
106- logger.trace("Created connection pool to host {}", host);
107- phase.compareAndSet(Phase.INITIALIZING, Phase.READY);
108- initFuture.set(null);
109- }
110- }
111-
112- @Override
113- public void onFailure(Throwable t) {
114- phase.compareAndSet(Phase.INITIALIZING, Phase.INIT_FAILED);
115- initFuture.setException(t);
116- }
117- }, initExecutor);
118-
119- return initFuture;
120- }
121-
122- private PoolingOptions options() {
123- return manager.configuration().getPoolingOptions();
124- }
125-
126- @Override
127- public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
128- Phase phase = this.phase.get();
129- if (phase != Phase.READY)
130- // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
131- // That being said, maybe having a specific exception could be cleaner.
132- throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
133-
134- Connection connection = connectionRef.get();
135- if (connection == null) {
136- if (scheduledForCreation.compareAndSet(false, true))
137- manager.blockingExecutor().submit(newConnectionTask);
138- connection = waitForConnection(timeout, unit);
139- } else {
140- while (true) {
141- int inFlight = connection.inFlight.get();
142-
143- if (inFlight >= Math.min(connection.maxAvailableStreams(),
144- options().getMaxSimultaneousRequestsPerHostThreshold(hostDistance))) {
145- connection = waitForConnection(timeout, unit);
146- break;
147- }
148-
149- if (connection.inFlight.compareAndSet(inFlight, inFlight + 1))
150- break;
151- }
152- }
153- connection.setKeyspace(manager.poolsState.keyspace);
154- return connection;
155- }
156-
157- private void awaitAvailableConnection(long timeout, TimeUnit unit) throws InterruptedException {
158- waitLock.lock();
159- waiter++;
160- try {
161- hasAvailableConnection.await(timeout, unit);
162- } finally {
163- waiter--;
164- waitLock.unlock();
165- }
166- }
167-
168- private void signalAvailableConnection() {
169- // Quick check if it's worth signaling to avoid locking
170- if (waiter == 0)
171- return;
172-
173- waitLock.lock();
174- try {
175- hasAvailableConnection.signal();
176- } finally {
177- waitLock.unlock();
178- }
179- }
180-
181- private void signalAllAvailableConnection() {
182- // Quick check if it's worth signaling to avoid locking
183- if (waiter == 0)
184- return;
185-
186- waitLock.lock();
187- try {
188- hasAvailableConnection.signalAll();
189- } finally {
190- waitLock.unlock();
191- }
192- }
193-
194- private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
195- if (timeout == 0)
196- throw new TimeoutException();
197-
198- long start = System.nanoTime();
199- long remaining = timeout;
200- do {
201- try {
202- awaitAvailableConnection(remaining, unit);
203- } catch (InterruptedException e) {
204- Thread.currentThread().interrupt();
205- // If we're interrupted fine, check if there is a connection available but stop waiting otherwise
206- timeout = 0; // this will make us stop the loop if we don't get a connection right away
207- }
208-
209- if (isClosed())
210- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
211-
212- Connection connection = connectionRef.get();
213- // If we race with shutdown, connection could be null. In that case we just loop and we'll throw on the next
214- // iteration anyway
215- if (connection != null) {
216- while (true) {
217- int inFlight = connection.inFlight.get();
218-
219- if (inFlight >= Math.min(connection.maxAvailableStreams(),
220- options().getMaxSimultaneousRequestsPerHostThreshold(hostDistance)))
221- break;
222-
223- if (connection.inFlight.compareAndSet(inFlight, inFlight + 1))
224- return connection;
225- }
226- }
227-
228- remaining = timeout - Cluster.timeSince(start, unit);
229- } while (remaining > 0);
230-
231- throw new TimeoutException();
232- }
233-
234- @Override
235- public void returnConnection(Connection connection) {
236- int inFlight = connection.inFlight.decrementAndGet();
237-
238- if (isClosed()) {
239- close(connection);
240- return;
241- }
242-
243- if (connection.isDefunct()) {
244- // As part of making it defunct, we have already replaced it or
245- // closed the pool.
246- return;
247- }
248-
249- if (trash.contains(connection)) {
250- if (inFlight == 0 && trash.remove(connection))
251- close(connection);
252- } else {
253- if (connection.maxAvailableStreams() < MIN_AVAILABLE_STREAMS) {
254- replaceConnection(connection);
255- } else {
256- signalAvailableConnection();
257- }
258- }
259- }
260-
261- // Trash the connection and create a new one, but we don't call trashConnection
262- // directly because we want to make sure the connection is always trashed.
263- private void replaceConnection(Connection connection) {
264- if (!connection.state.compareAndSet(OPEN, TRASHED))
265- return;
266- open.set(false);
267- maybeSpawnNewConnection();
268- doTrashConnection(connection);
269- }
270-
271- private void doTrashConnection(Connection connection) {
272- connectionRef.compareAndSet(connection, null);
273- trash.add(connection);
274-
275- if (connection.inFlight.get() == 0 && trash.remove(connection))
276- close(connection);
277- }
278-
279- private boolean addConnectionIfNeeded() {
280- if (!open.compareAndSet(false, true))
281- return false;
282-
283- if (phase.get() != Phase.READY) {
284- open.set(false);
285- return false;
286- }
287-
288- // Now really open the connection
289- try {
290- logger.debug("Creating new connection on busy pool to {}", host);
291- Connection newConnection = manager.connectionFactory().open(this);
292- connectionRef.set(newConnection);
293-
294- // We might have raced with pool shutdown since the last check; ensure the connection gets closed in case the pool did not do it.
295- if (isClosed() && !newConnection.isClosed()) {
296- close(newConnection);
297- this.open.set(false);
298- return false;
299- }
300-
301- signalAvailableConnection();
302- return true;
303- } catch (InterruptedException e) {
304- Thread.currentThread().interrupt();
305- // Skip the open but ignore otherwise
306- open.set(false);
307- return false;
308- } catch (ConnectionException e) {
309- open.set(false);
310- logger.debug("Connection error to {} while creating additional connection", host);
311- return false;
312- } catch (AuthenticationException e) {
313- // This shouldn't really happen in theory
314- open.set(false);
315- logger.error("Authentication error while creating additional connection (error is: {})", e.getMessage());
316- return false;
317- } catch (UnsupportedProtocolVersionException e) {
318- // This shouldn't happen since we shouldn't have been able to connect in the first place
319- open.set(false);
320- logger.error("UnsupportedProtocolVersionException error while creating additional connection (error is: {})", e.getMessage());
321- return false;
322- } catch (ClusterNameMismatchException e) {
323- open.set(false);
324- logger.error("ClusterNameMismatchException error while creating additional connection (error is: {})", e.getMessage());
325- return false;
326- }
327- }
328-
329- private void maybeSpawnNewConnection() {
330- if (!scheduledForCreation.compareAndSet(false, true))
331- return;
332-
333- manager.blockingExecutor().submit(newConnectionTask);
334- }
335-
336- @Override
337- public void replaceDefunctConnection(final Connection connection) {
338- if (connection.state.compareAndSet(OPEN, GONE))
339- open.set(false);
340- if (connectionRef.compareAndSet(connection, null))
341- manager.blockingExecutor().submit(new Runnable() {
342- @Override
343- public void run() {
344- addConnectionIfNeeded();
345- }
346- });
347- }
348-
349- @Override
350- void cleanupIdleConnections(long now) {
351- }
352-
353- private void close(final Connection connection) {
354- connection.closeAsync();
355- }
356-
357- protected CloseFuture makeCloseFuture() {
358- // Wake up all threads that wait
359- signalAllAvailableConnection();
360-
361- return new CloseFuture.Forwarding(discardConnection());
362- }
363-
364- private List<CloseFuture> discardConnection() {
365-
366- List<CloseFuture> futures = new ArrayList<CloseFuture>();
367-
368- final Connection connection = connectionRef.get();
369- if (connection != null) {
370- CloseFuture future = connection.closeAsync();
371- future.addListener(new Runnable() {
372- public void run() {
373- if (connection.state.compareAndSet(OPEN, GONE))
374- open.set(false);
375- }
376- }, MoreExecutors.sameThreadExecutor());
377- futures.add(future);
378- }
379- return futures;
380- }
381-
382- @Override
383- public void ensureCoreConnections() {
384- if (isClosed())
385- return;
386-
387- if (!open.get() && scheduledForCreation.compareAndSet(false, true)) {
388- manager.blockingExecutor().submit(newConnectionTask);
389- }
390- }
391-
392- @Override
393- public int opened() {
394- return open.get() ? 1 : 0;
395- }
396-
397- @Override
398- int trashed() {
399- return trash.size();
400- }
401-
402- @Override
403- public int inFlightQueriesCount() {
404- Connection connection = connectionRef.get();
405- return connection == null ? 0 : connection.inFlight.get();
406- }
407-}
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +4 −9
@@ -21,7 +21,8 @@
2121 import com.google.common.collect.Lists;
2222 import org.testng.annotations.Test;
2323
24-import static org.testng.Assert.*;
24+import static org.testng.Assert.assertEquals;
25+import static org.testng.Assert.assertTrue;
2526
2627 public class AsyncQueryTest extends CCMBridge.PerClassSingleNodeCluster {
2728
@@ -42,14 +43,8 @@
4243 TimeUnit.MILLISECONDS.sleep(100);
4344
4445 HostConnectionPool pool = getPool(session);
45- if (pool instanceof DynamicConnectionPool) {
46- DynamicConnectionPool p = (DynamicConnectionPool)pool;
47- for (Connection connection : p.connections) {
48- assertEquals(connection.inFlight.get(), 0);
49- }
50- } else if (pool instanceof SingleConnectionPool){
51- SingleConnectionPool p = (SingleConnectionPool)pool;
52- assertEquals(p.connectionRef.get().inFlight.get(), 0);
46+ for (Connection connection : pool.connections) {
47+ assertEquals(connection.inFlight.get(), 0);
5348 }
5449 }
5550
deleted driver-core/src/test/java/com/datastax/driver/core/DynamicConnectionPoolTest.java +0 −432
@@ -1,432 +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.util.Collection;
19-import java.util.List;
20-import java.util.concurrent.*;
21-import java.util.concurrent.atomic.AtomicBoolean;
22-
23-import static java.util.concurrent.TimeUnit.MILLISECONDS;
24-import static java.util.concurrent.TimeUnit.SECONDS;
25-
26-import com.codahale.metrics.Gauge;
27-import com.google.common.collect.Lists;
28-import org.testng.annotations.Test;
29-
30-import static org.assertj.core.api.Assertions.assertThat;
31-import static org.mockito.Mockito.doReturn;
32-import static org.mockito.Mockito.spy;
33-import static org.testng.Assert.fail;
34-
35-public class DynamicConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster {
36- @Override
37- protected Collection<String> getTableDefinitions() {
38- StringBuilder sb = new StringBuilder("CREATE TABLE Java349 (mykey INT primary key");
39- for (int i = 0; i < 1000; i++) {
40- sb.append(", column").append(i).append(" INT");
41- }
42- sb.append(")");
43- return Lists.newArrayList(sb.toString());
44- }
45-
46- @Override
47- protected Cluster.Builder configure(Cluster.Builder builder) {
48- // Use version 2 at highest.
49- ProtocolVersion versionToUse = TestUtils.getDesiredProtocolVersion();
50- versionToUse = versionToUse == ProtocolVersion.V3 ? ProtocolVersion.V2 : versionToUse;
51- return builder.withProtocolVersion(versionToUse);
52- }
53-
54- /**
55- * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead
56- * of creating a new connection.
57- *
58- * @since 2.0.10, 2.1.6
59- * @jira_ticket JAVA-419
60- * @test_category connection:connection_pool
61- */
62- @Test(groups = "short")
63- public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException {
64- DynamicConnectionPool pool = createPool(2, 2);
65-
66- assertThat(pool.connections.size()).isEqualTo(2);
67- List<Connection> coreConnections = Lists.newArrayList(pool.connections);
68-
69- for (int i = 0; i < 256; i++) {
70- Connection connection = pool.borrowConnection(100, MILLISECONDS);
71- assertThat(coreConnections).contains(connection);
72- }
73-
74- boolean timedOut = false;
75- try {
76- pool.borrowConnection(100, MILLISECONDS);
77- } catch (TimeoutException e) {
78- timedOut = true;
79- }
80- assertThat(timedOut).isTrue();
81- }
82-
83- /**
84- * Ensures that if a variable-sized pool has filled up to its maximum connections that borrowConnection will
85- * timeout instead of creating a new connection.
86- *
87- * @since 2.0.10, 2.1.6
88- * @jira_ticket JAVA-419
89- * @test_category connection:connection_pool
90- */
91- @Test(groups = "short")
92- public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws ConnectionException, TimeoutException {
93- DynamicConnectionPool pool = createPool(1, 2);
94-
95- assertThat(pool.connections.size()).isEqualTo(1);
96- List<Connection> coreConnections = Lists.newArrayList(pool.connections);
97-
98- //
99- for (int i = 0; i < 128; i++) {
100- Connection connection = pool.borrowConnection(100, MILLISECONDS);
101- assertThat(coreConnections).contains(connection);
102- }
103-
104- // Borrow more and ensure the connection returned is a non-core connection.
105- for (int i = 0; i < 128; i++) {
106- Connection connection = pool.borrowConnection(100, MILLISECONDS);
107- assertThat(coreConnections).doesNotContain(connection);
108- }
109-
110- boolean timedOut = false;
111- try {
112- pool.borrowConnection(100, MILLISECONDS);
113- } catch (TimeoutException e) {
114- timedOut = true;
115- }
116- assertThat(timedOut).isTrue();
117- }
118-
119- /**
120- * Ensures that if the core connection pool is full that borrowConnection will create and use a new connection.
121- *
122- * @since 2.0.10, 2.1.6
123- * @jira_ticket JAVA-419
124- * @test_category connection:connection_pool
125- */
126- @Test(groups = "short")
127- public void should_add_extra_connection_when_core_full() throws ConnectionException, TimeoutException, InterruptedException {
128- cluster.getConfiguration().getPoolingOptions()
129- .setIdleTimeoutSeconds(20);
130-
131- DynamicConnectionPool pool = createPool(1, 2);
132- Connection core = pool.connections.get(0);
133-
134- // Fill core connection
135- for (int i = 0; i < 128; i++)
136- assertThat(
137- pool.borrowConnection(100, MILLISECONDS)
138- ).isEqualTo(core);
139-
140- // Reaching 128 on the core connection should have triggered the creation of an extra one
141- TimeUnit.MILLISECONDS.sleep(100);
142- assertThat(pool.connections).hasSize(2);
143- }
144-
145- /**
146- * Ensures that a trashed connection that has not been timed out should be resurrected into the connection pool if
147- * borrowConnection is called and a new connection is needed.
148- *
149- * @since 2.0.10, 2.1.6
150- * @jira_ticket JAVA-419
151- * @test_category connection:connection_pool
152- */
153- @Test(groups = "long")
154- public void should_resurrect_trashed_connection_within_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
155- cluster.getConfiguration().getPoolingOptions()
156- .setIdleTimeoutSeconds(20);
157-
158- DynamicConnectionPool pool = createPool(1, 2);
159- Connection connection1 = pool.connections.get(0);
160-
161- for (int i = 0; i < 101; i++)
162- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
163-
164- TimeUnit.MILLISECONDS.sleep(100);
165- assertThat(pool.connections).hasSize(2);
166- Connection connection2 = pool.connections.get(1);
167-
168- assertThat(connection1.inFlight.get()).isEqualTo(101);
169- assertThat(connection2.inFlight.get()).isEqualTo(0);
170-
171- // Go back under the capacity of 1 connection
172- for (int i = 0; i < 51; i++)
173- pool.returnConnection(connection1);
174-
175- assertThat(connection1.inFlight.get()).isEqualTo(50);
176- assertThat(connection2.inFlight.get()).isEqualTo(0);
177-
178- // Given enough time, one connection gets trashed (and the implementation picks the first one)
179- TimeUnit.SECONDS.sleep(20);
180- assertThat(pool.connections).containsExactly(connection2);
181- assertThat(pool.trash).containsExactly(connection1);
182-
183- // Now borrow enough to go just under the 1 connection threshold
184- for (int i = 0; i < 50; i++)
185- pool.borrowConnection(100, MILLISECONDS);
186-
187- assertThat(pool.connections).containsExactly(connection2);
188- assertThat(pool.trash).containsExactly(connection1);
189- assertThat(connection1.inFlight.get()).isEqualTo(50);
190- assertThat(connection2.inFlight.get()).isEqualTo(50);
191-
192- // Borrowing one more time should resurrect the trashed connection
193- pool.borrowConnection(100, MILLISECONDS);
194- TimeUnit.MILLISECONDS.sleep(100);
195-
196- assertThat(pool.connections).containsExactly(connection2, connection1);
197- assertThat(pool.trash).isEmpty();
198- assertThat(connection1.inFlight.get()).isEqualTo(50);
199- assertThat(connection2.inFlight.get()).isEqualTo(51);
200- }
201-
202- /**
203- * Ensures that a trashed connection that has been timed out should not be resurrected into the connection pool if
204- * borrowConnection is called and a new connection is needed.
205- *
206- * @since 2.0.10, 2.1.6
207- * @jira_ticket JAVA-419
208- * @test_category connection:connection_pool
209- */
210- @Test(groups = "long")
211- public void should_not_resurrect_trashed_connection_after_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
212- cluster.getConfiguration().getPoolingOptions()
213- .setIdleTimeoutSeconds(20);
214-
215- DynamicConnectionPool pool = createPool(1, 2);
216- Connection connection1 = pool.connections.get(0);
217-
218- for (int i = 0; i < 101; i++)
219- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
220-
221- TimeUnit.MILLISECONDS.sleep(100);
222- assertThat(pool.connections).hasSize(2);
223- Connection connection2 = pool.connections.get(1);
224-
225- assertThat(connection1.inFlight.get()).isEqualTo(101);
226- assertThat(connection2.inFlight.get()).isEqualTo(0);
227-
228- // Go back under the capacity of 1 connection
229- for (int i = 0; i < 51; i++)
230- pool.returnConnection(connection1);
231-
232- assertThat(connection1.inFlight.get()).isEqualTo(50);
233- assertThat(connection2.inFlight.get()).isEqualTo(0);
234-
235- // Given enough time, one connection gets trashed (and the implementation picks the first one)
236- TimeUnit.SECONDS.sleep(20);
237- assertThat(pool.connections).containsExactly(connection2);
238- assertThat(pool.trash).containsExactly(connection1);
239-
240- // Return trashed connection down to 0 inFlight
241- for (int i = 0; i < 50; i++)
242- pool.returnConnection(connection1);
243- assertThat(connection1.inFlight.get()).isEqualTo(0);
244-
245- // Give enough time for trashed connection to be cleaned up from the trash:
246- TimeUnit.SECONDS.sleep(30);
247- assertThat(pool.connections).containsExactly(connection2);
248- assertThat(pool.trash).isEmpty();
249- assertThat(connection1.isClosed()).isTrue();
250-
251- // Fill the live connection to go over the threshold where a second one is needed
252- for (int i = 0; i < 101; i++)
253- assertThat(pool.borrowConnection(100, TimeUnit.MILLISECONDS)).isEqualTo(connection2);
254- assertThat(connection2.inFlight.get()).isEqualTo(101);
255- TimeUnit.MILLISECONDS.sleep(100);
256-
257- // Borrow again to get the new connection
258- Connection connection3 = pool.borrowConnection(100, MILLISECONDS);
259- assertThat(connection3)
260- .isNotEqualTo(connection2) // should not be the full connection
261- .isNotEqualTo(connection1); // should not be the previously trashed one
262- }
263-
264- /**
265- * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
266- *
267- * @since 2.0.10, 2.1.6
268- * @jira_ticket JAVA-419
269- * @test_category connection:connection_pool
270- */
271- @Test(groups = "long")
272- public void should_not_close_trashed_connection_until_no_in_flight()
273- throws ConnectionException, TimeoutException, InterruptedException {
274- cluster.getConfiguration().getPoolingOptions()
275- .setIdleTimeoutSeconds(20);
276-
277- DynamicConnectionPool pool = createPool(1, 2);
278- Connection connection1 = pool.connections.get(0);
279-
280- // Fill core connection enough to trigger creation of another one
281- for (int i = 0; i < 110; i++)
282- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
283-
284- TimeUnit.MILLISECONDS.sleep(100);
285- assertThat(pool.connections).hasSize(2);
286-
287- // Return enough times to get back under the threshold where one connection is enough
288- for (int i = 0; i < 50; i++)
289- pool.returnConnection(connection1);
290-
291- // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
292- // It still has in-flight requests so should not get closed.
293- TimeUnit.SECONDS.sleep(30);
294- assertThat(pool.trash).containsExactly(connection1);
295- assertThat(connection1.inFlight.get()).isEqualTo(60);
296- assertThat(connection1.isClosed()).isFalse();
297-
298- // Consume all inFlight requests on the trashed connection.
299- while (connection1.inFlight.get() > 0) {
300- pool.returnConnection(connection1);
301- }
302-
303- // Sleep enough time for the connection to be consider idled and closed.
304- TimeUnit.SECONDS.sleep(30);
305-
306- // The connection should be now closed.
307- // The trashed connection should be closed and not in the pool or trash.
308- assertThat(connection1.isClosed()).isTrue();
309- assertThat(pool.connections).doesNotContain(connection1);
310- assertThat(pool.trash).doesNotContain(connection1);
311- }
312-
313- /**
314- * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
315- * the connection is put in the trash.
316- *
317- * @since 2.0.10, 2.1.6
318- * @jira_ticket JAVA-419
319- * @test_category connection:connection_pool
320- */
321- @Test(groups = "short")
322- public void should_trash_on_returning_connection_with_insufficient_streams()
323- throws ConnectionException, TimeoutException, InterruptedException {
324- DynamicConnectionPool pool = createPool(1, 2);
325- Connection core = pool.connections.get(0);
326-
327- for (int i = 0; i < 128; i++)
328- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core);
329-
330- TimeUnit.MILLISECONDS.sleep(100);
331- assertThat(pool.connections).hasSize(2);
332-
333- // Grab the new non-core connection and replace it with a spy.
334- Connection extra1 = spy(pool.connections.get(1));
335- pool.connections.set(1, extra1);
336-
337- // Borrow 10 times to ensure pool is utilized.
338- for (int i = 0; i < 10; i++) {
339- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(extra1);
340- }
341-
342- // Return connection, it should not be trashed since it still has 9 inflight requests.
343- pool.returnConnection(extra1);
344- assertThat(pool.connections).hasSize(2);
345-
346- // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
347- // this should cause the connection to be replaced and trashed on returnConnection.
348- doReturn(0).when(extra1).maxAvailableStreams();
349-
350- // On returning of the connection, should detect that there are no available streams and trash it.
351- pool.returnConnection(extra1);
352- assertThat(pool.connections).hasSize(1);
353- }
354-
355- private DynamicConnectionPool createPool(int coreConnections, int maxConnections) {
356- cluster.getConfiguration().getPoolingOptions()
357- .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections)
358- .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections);
359- Session session = cluster.connect();
360- Host host = TestUtils.findHost(cluster, 1);
361- return (DynamicConnectionPool)((SessionManager)session).pools.get(host);
362- }
363-
364- /**
365- * <p>
366- * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the
367- * insertions are being executed, the number of opened connection is monitored.
368- * <p/>
369- * If at anytime, the number of opened connections is negative, this test will fail.
370- *
371- * @since 2.0.6, 2.1.1
372- * @jira_ticket JAVA-349
373- * @test_category connection:connection_pool
374- */
375- @Test(groups = "long", enabled = false /* this test causes timeouts on Jenkins */)
376- public void open_connections_metric_should_always_be_positive() throws InterruptedException {
377- // Track progress in a dedicated thread
378- int numberOfInserts = 100 * 1000;
379- final CountDownLatch pendingInserts = new CountDownLatch(numberOfInserts);
380- ExecutorService progressReportExecutor = Executors.newSingleThreadExecutor();
381- final Runnable progressReporter = new Runnable() {
382- @Override
383- public void run() {
384- pendingInserts.countDown();
385- }
386- };
387-
388- // Track opened connections in a dedicated thread every one second
389- final AtomicBoolean negativeOpenConnectionCountSpotted = new AtomicBoolean(false);
390- final Gauge<Integer> openConnections = cluster.getMetrics().getOpenConnections();
391- ScheduledExecutorService openConnectionsWatcherExecutor = Executors.newScheduledThreadPool(1);
392- final Runnable openConnectionsWatcher = new Runnable() {
393- @Override
394- public void run() {
395- Integer value = openConnections.getValue();
396- if (value < 0) {
397- System.err.println("Negative value spotted for openConnection metric: " + value);
398- negativeOpenConnectionCountSpotted.set(true);
399- }
400- }
401- };
402- openConnectionsWatcherExecutor.scheduleAtFixedRate(openConnectionsWatcher, 1, 1, SECONDS);
403-
404- // Insert 100k lines in a newly created 1k columns table
405- PreparedStatement insertStatement = session.prepare(generateJava349InsertStatement());
406- for (int key = 0; key < numberOfInserts; key++) {
407- session.executeAsync(insertStatement.bind(key)).addListener(progressReporter, progressReportExecutor);
408- }
409-
410- // Wait for all inserts to happen and stop connections and progress tracking
411- pendingInserts.await();
412- openConnectionsWatcherExecutor.shutdownNow();
413- progressReportExecutor.shutdownNow();
414-
415- if (negativeOpenConnectionCountSpotted.get()) {
416- fail("Negative value spotted for open connection count");
417- }
418- }
419-
420- private String generateJava349InsertStatement() {
421- StringBuilder sb = new StringBuilder("INSERT INTO Java349 (mykey");
422- for (int i = 0; i < 1000; i++) {
423- sb.append(", column").append(i);
424- }
425- sb.append(") VALUES (?");
426- for (int i = 0; i < 1000; i++) {
427- sb.append(", ").append(i);
428- }
429- sb.append(");");
430- return sb.toString();
431- }
432-}
added driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +432 −0
@@ -0,0 +1,432 @@
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.util.Collection;
19+import java.util.List;
20+import java.util.concurrent.*;
21+import java.util.concurrent.atomic.AtomicBoolean;
22+
23+import static java.util.concurrent.TimeUnit.MILLISECONDS;
24+import static java.util.concurrent.TimeUnit.SECONDS;
25+
26+import com.codahale.metrics.Gauge;
27+import com.google.common.collect.Lists;
28+import org.testng.annotations.Test;
29+
30+import static org.assertj.core.api.Assertions.assertThat;
31+import static org.mockito.Mockito.doReturn;
32+import static org.mockito.Mockito.spy;
33+import static org.testng.Assert.fail;
34+
35+public class HostConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster {
36+ @Override
37+ protected Collection<String> getTableDefinitions() {
38+ StringBuilder sb = new StringBuilder("CREATE TABLE Java349 (mykey INT primary key");
39+ for (int i = 0; i < 1000; i++) {
40+ sb.append(", column").append(i).append(" INT");
41+ }
42+ sb.append(")");
43+ return Lists.newArrayList(sb.toString());
44+ }
45+
46+ @Override
47+ protected Cluster.Builder configure(Cluster.Builder builder) {
48+ // Use version 2 at highest.
49+ ProtocolVersion versionToUse = TestUtils.getDesiredProtocolVersion();
50+ versionToUse = versionToUse == ProtocolVersion.V3 ? ProtocolVersion.V2 : versionToUse;
51+ return builder.withProtocolVersion(versionToUse);
52+ }
53+
54+ /**
55+ * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead
56+ * of creating a new connection.
57+ *
58+ * @since 2.0.10, 2.1.6
59+ * @jira_ticket JAVA-419
60+ * @test_category connection:connection_pool
61+ */
62+ @Test(groups = "short")
63+ public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException {
64+ HostConnectionPool pool = createPool(2, 2);
65+
66+ assertThat(pool.connections.size()).isEqualTo(2);
67+ List<Connection> coreConnections = Lists.newArrayList(pool.connections);
68+
69+ for (int i = 0; i < 256; i++) {
70+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
71+ assertThat(coreConnections).contains(connection);
72+ }
73+
74+ boolean timedOut = false;
75+ try {
76+ pool.borrowConnection(100, MILLISECONDS);
77+ } catch (TimeoutException e) {
78+ timedOut = true;
79+ }
80+ assertThat(timedOut).isTrue();
81+ }
82+
83+ /**
84+ * Ensures that if a variable-sized pool has filled up to its maximum connections that borrowConnection will
85+ * timeout instead of creating a new connection.
86+ *
87+ * @since 2.0.10, 2.1.6
88+ * @jira_ticket JAVA-419
89+ * @test_category connection:connection_pool
90+ */
91+ @Test(groups = "short")
92+ public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws ConnectionException, TimeoutException {
93+ HostConnectionPool pool = createPool(1, 2);
94+
95+ assertThat(pool.connections.size()).isEqualTo(1);
96+ List<Connection> coreConnections = Lists.newArrayList(pool.connections);
97+
98+ //
99+ for (int i = 0; i < 128; i++) {
100+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
101+ assertThat(coreConnections).contains(connection);
102+ }
103+
104+ // Borrow more and ensure the connection returned is a non-core connection.
105+ for (int i = 0; i < 128; i++) {
106+ Connection connection = pool.borrowConnection(100, MILLISECONDS);
107+ assertThat(coreConnections).doesNotContain(connection);
108+ }
109+
110+ boolean timedOut = false;
111+ try {
112+ pool.borrowConnection(100, MILLISECONDS);
113+ } catch (TimeoutException e) {
114+ timedOut = true;
115+ }
116+ assertThat(timedOut).isTrue();
117+ }
118+
119+ /**
120+ * Ensures that if the core connection pool is full that borrowConnection will create and use a new connection.
121+ *
122+ * @since 2.0.10, 2.1.6
123+ * @jira_ticket JAVA-419
124+ * @test_category connection:connection_pool
125+ */
126+ @Test(groups = "short")
127+ public void should_add_extra_connection_when_core_full() throws ConnectionException, TimeoutException, InterruptedException {
128+ cluster.getConfiguration().getPoolingOptions()
129+ .setIdleTimeoutSeconds(20);
130+
131+ HostConnectionPool pool = createPool(1, 2);
132+ Connection core = pool.connections.get(0);
133+
134+ // Fill core connection
135+ for (int i = 0; i < 128; i++)
136+ assertThat(
137+ pool.borrowConnection(100, MILLISECONDS)
138+ ).isEqualTo(core);
139+
140+ // Reaching 128 on the core connection should have triggered the creation of an extra one
141+ TimeUnit.MILLISECONDS.sleep(100);
142+ assertThat(pool.connections).hasSize(2);
143+ }
144+
145+ /**
146+ * Ensures that a trashed connection that has not been timed out should be resurrected into the connection pool if
147+ * borrowConnection is called and a new connection is needed.
148+ *
149+ * @since 2.0.10, 2.1.6
150+ * @jira_ticket JAVA-419
151+ * @test_category connection:connection_pool
152+ */
153+ @Test(groups = "long")
154+ public void should_resurrect_trashed_connection_within_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
155+ cluster.getConfiguration().getPoolingOptions()
156+ .setIdleTimeoutSeconds(20);
157+
158+ HostConnectionPool pool = createPool(1, 2);
159+ Connection connection1 = pool.connections.get(0);
160+
161+ for (int i = 0; i < 101; i++)
162+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
163+
164+ TimeUnit.MILLISECONDS.sleep(100);
165+ assertThat(pool.connections).hasSize(2);
166+ Connection connection2 = pool.connections.get(1);
167+
168+ assertThat(connection1.inFlight.get()).isEqualTo(101);
169+ assertThat(connection2.inFlight.get()).isEqualTo(0);
170+
171+ // Go back under the capacity of 1 connection
172+ for (int i = 0; i < 51; i++)
173+ pool.returnConnection(connection1);
174+
175+ assertThat(connection1.inFlight.get()).isEqualTo(50);
176+ assertThat(connection2.inFlight.get()).isEqualTo(0);
177+
178+ // Given enough time, one connection gets trashed (and the implementation picks the first one)
179+ TimeUnit.SECONDS.sleep(20);
180+ assertThat(pool.connections).containsExactly(connection2);
181+ assertThat(pool.trash).containsExactly(connection1);
182+
183+ // Now borrow enough to go just under the 1 connection threshold
184+ for (int i = 0; i < 50; i++)
185+ pool.borrowConnection(100, MILLISECONDS);
186+
187+ assertThat(pool.connections).containsExactly(connection2);
188+ assertThat(pool.trash).containsExactly(connection1);
189+ assertThat(connection1.inFlight.get()).isEqualTo(50);
190+ assertThat(connection2.inFlight.get()).isEqualTo(50);
191+
192+ // Borrowing one more time should resurrect the trashed connection
193+ pool.borrowConnection(100, MILLISECONDS);
194+ TimeUnit.MILLISECONDS.sleep(100);
195+
196+ assertThat(pool.connections).containsExactly(connection2, connection1);
197+ assertThat(pool.trash).isEmpty();
198+ assertThat(connection1.inFlight.get()).isEqualTo(50);
199+ assertThat(connection2.inFlight.get()).isEqualTo(51);
200+ }
201+
202+ /**
203+ * Ensures that a trashed connection that has been timed out should not be resurrected into the connection pool if
204+ * borrowConnection is called and a new connection is needed.
205+ *
206+ * @since 2.0.10, 2.1.6
207+ * @jira_ticket JAVA-419
208+ * @test_category connection:connection_pool
209+ */
210+ @Test(groups = "long")
211+ public void should_not_resurrect_trashed_connection_after_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
212+ cluster.getConfiguration().getPoolingOptions()
213+ .setIdleTimeoutSeconds(20);
214+
215+ HostConnectionPool pool = createPool(1, 2);
216+ Connection connection1 = pool.connections.get(0);
217+
218+ for (int i = 0; i < 101; i++)
219+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
220+
221+ TimeUnit.MILLISECONDS.sleep(100);
222+ assertThat(pool.connections).hasSize(2);
223+ Connection connection2 = pool.connections.get(1);
224+
225+ assertThat(connection1.inFlight.get()).isEqualTo(101);
226+ assertThat(connection2.inFlight.get()).isEqualTo(0);
227+
228+ // Go back under the capacity of 1 connection
229+ for (int i = 0; i < 51; i++)
230+ pool.returnConnection(connection1);
231+
232+ assertThat(connection1.inFlight.get()).isEqualTo(50);
233+ assertThat(connection2.inFlight.get()).isEqualTo(0);
234+
235+ // Given enough time, one connection gets trashed (and the implementation picks the first one)
236+ TimeUnit.SECONDS.sleep(20);
237+ assertThat(pool.connections).containsExactly(connection2);
238+ assertThat(pool.trash).containsExactly(connection1);
239+
240+ // Return trashed connection down to 0 inFlight
241+ for (int i = 0; i < 50; i++)
242+ pool.returnConnection(connection1);
243+ assertThat(connection1.inFlight.get()).isEqualTo(0);
244+
245+ // Give enough time for trashed connection to be cleaned up from the trash:
246+ TimeUnit.SECONDS.sleep(30);
247+ assertThat(pool.connections).containsExactly(connection2);
248+ assertThat(pool.trash).isEmpty();
249+ assertThat(connection1.isClosed()).isTrue();
250+
251+ // Fill the live connection to go over the threshold where a second one is needed
252+ for (int i = 0; i < 101; i++)
253+ assertThat(pool.borrowConnection(100, TimeUnit.MILLISECONDS)).isEqualTo(connection2);
254+ assertThat(connection2.inFlight.get()).isEqualTo(101);
255+ TimeUnit.MILLISECONDS.sleep(100);
256+
257+ // Borrow again to get the new connection
258+ Connection connection3 = pool.borrowConnection(100, MILLISECONDS);
259+ assertThat(connection3)
260+ .isNotEqualTo(connection2) // should not be the full connection
261+ .isNotEqualTo(connection1); // should not be the previously trashed one
262+ }
263+
264+ /**
265+ * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
266+ *
267+ * @since 2.0.10, 2.1.6
268+ * @jira_ticket JAVA-419
269+ * @test_category connection:connection_pool
270+ */
271+ @Test(groups = "long")
272+ public void should_not_close_trashed_connection_until_no_in_flight()
273+ throws ConnectionException, TimeoutException, InterruptedException {
274+ cluster.getConfiguration().getPoolingOptions()
275+ .setIdleTimeoutSeconds(20);
276+
277+ HostConnectionPool pool = createPool(1, 2);
278+ Connection connection1 = pool.connections.get(0);
279+
280+ // Fill core connection enough to trigger creation of another one
281+ for (int i = 0; i < 110; i++)
282+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
283+
284+ TimeUnit.MILLISECONDS.sleep(100);
285+ assertThat(pool.connections).hasSize(2);
286+
287+ // Return enough times to get back under the threshold where one connection is enough
288+ for (int i = 0; i < 50; i++)
289+ pool.returnConnection(connection1);
290+
291+ // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
292+ // It still has in-flight requests so should not get closed.
293+ TimeUnit.SECONDS.sleep(30);
294+ assertThat(pool.trash).containsExactly(connection1);
295+ assertThat(connection1.inFlight.get()).isEqualTo(60);
296+ assertThat(connection1.isClosed()).isFalse();
297+
298+ // Consume all inFlight requests on the trashed connection.
299+ while (connection1.inFlight.get() > 0) {
300+ pool.returnConnection(connection1);
301+ }
302+
303+ // Sleep enough time for the connection to be consider idled and closed.
304+ TimeUnit.SECONDS.sleep(30);
305+
306+ // The connection should be now closed.
307+ // The trashed connection should be closed and not in the pool or trash.
308+ assertThat(connection1.isClosed()).isTrue();
309+ assertThat(pool.connections).doesNotContain(connection1);
310+ assertThat(pool.trash).doesNotContain(connection1);
311+ }
312+
313+ /**
314+ * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
315+ * the connection is put in the trash.
316+ *
317+ * @since 2.0.10, 2.1.6
318+ * @jira_ticket JAVA-419
319+ * @test_category connection:connection_pool
320+ */
321+ @Test(groups = "short")
322+ public void should_trash_on_returning_connection_with_insufficient_streams()
323+ throws ConnectionException, TimeoutException, InterruptedException {
324+ HostConnectionPool pool = createPool(1, 2);
325+ Connection core = pool.connections.get(0);
326+
327+ for (int i = 0; i < 128; i++)
328+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core);
329+
330+ TimeUnit.MILLISECONDS.sleep(100);
331+ assertThat(pool.connections).hasSize(2);
332+
333+ // Grab the new non-core connection and replace it with a spy.
334+ Connection extra1 = spy(pool.connections.get(1));
335+ pool.connections.set(1, extra1);
336+
337+ // Borrow 10 times to ensure pool is utilized.
338+ for (int i = 0; i < 10; i++) {
339+ assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(extra1);
340+ }
341+
342+ // Return connection, it should not be trashed since it still has 9 inflight requests.
343+ pool.returnConnection(extra1);
344+ assertThat(pool.connections).hasSize(2);
345+
346+ // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
347+ // this should cause the connection to be replaced and trashed on returnConnection.
348+ doReturn(0).when(extra1).maxAvailableStreams();
349+
350+ // On returning of the connection, should detect that there are no available streams and trash it.
351+ pool.returnConnection(extra1);
352+ assertThat(pool.connections).hasSize(1);
353+ }
354+
355+ private HostConnectionPool createPool(int coreConnections, int maxConnections) {
356+ cluster.getConfiguration().getPoolingOptions()
357+ .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections)
358+ .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections);
359+ Session session = cluster.connect();
360+ Host host = TestUtils.findHost(cluster, 1);
361+ return (HostConnectionPool)((SessionManager)session).pools.get(host);
362+ }
363+
364+ /**
365+ * <p>
366+ * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the
367+ * insertions are being executed, the number of opened connection is monitored.
368+ * <p/>
369+ * If at anytime, the number of opened connections is negative, this test will fail.
370+ *
371+ * @since 2.0.6, 2.1.1
372+ * @jira_ticket JAVA-349
373+ * @test_category connection:connection_pool
374+ */
375+ @Test(groups = "long", enabled = false /* this test causes timeouts on Jenkins */)
376+ public void open_connections_metric_should_always_be_positive() throws InterruptedException {
377+ // Track progress in a dedicated thread
378+ int numberOfInserts = 100 * 1000;
379+ final CountDownLatch pendingInserts = new CountDownLatch(numberOfInserts);
380+ ExecutorService progressReportExecutor = Executors.newSingleThreadExecutor();
381+ final Runnable progressReporter = new Runnable() {
382+ @Override
383+ public void run() {
384+ pendingInserts.countDown();
385+ }
386+ };
387+
388+ // Track opened connections in a dedicated thread every one second
389+ final AtomicBoolean negativeOpenConnectionCountSpotted = new AtomicBoolean(false);
390+ final Gauge<Integer> openConnections = cluster.getMetrics().getOpenConnections();
391+ ScheduledExecutorService openConnectionsWatcherExecutor = Executors.newScheduledThreadPool(1);
392+ final Runnable openConnectionsWatcher = new Runnable() {
393+ @Override
394+ public void run() {
395+ Integer value = openConnections.getValue();
396+ if (value < 0) {
397+ System.err.println("Negative value spotted for openConnection metric: " + value);
398+ negativeOpenConnectionCountSpotted.set(true);
399+ }
400+ }
401+ };
402+ openConnectionsWatcherExecutor.scheduleAtFixedRate(openConnectionsWatcher, 1, 1, SECONDS);
403+
404+ // Insert 100k lines in a newly created 1k columns table
405+ PreparedStatement insertStatement = session.prepare(generateJava349InsertStatement());
406+ for (int key = 0; key < numberOfInserts; key++) {
407+ session.executeAsync(insertStatement.bind(key)).addListener(progressReporter, progressReportExecutor);
408+ }
409+
410+ // Wait for all inserts to happen and stop connections and progress tracking
411+ pendingInserts.await();
412+ openConnectionsWatcherExecutor.shutdownNow();
413+ progressReportExecutor.shutdownNow();
414+
415+ if (negativeOpenConnectionCountSpotted.get()) {
416+ fail("Negative value spotted for open connection count");
417+ }
418+ }
419+
420+ private String generateJava349InsertStatement() {
421+ StringBuilder sb = new StringBuilder("INSERT INTO Java349 (mykey");
422+ for (int i = 0; i < 1000; i++) {
423+ sb.append(", column").append(i);
424+ }
425+ sb.append(") VALUES (?");
426+ for (int i = 0; i < 1000; i++) {
427+ sb.append(", ").append(i);
428+ }
429+ sb.append(");");
430+ return sb.toString();
431+ }
432+}
modified driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java +1 −1
@@ -65,7 +65,7 @@
6565 cluster = Cluster.builder()
6666 .addContactPoint(ipOfNode(1))
6767 .withPoolingOptions(new PoolingOptions()
68- .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections)
68+ .setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)
6969 )
7070 .withNettyOptions(nettyOptions)
7171 .build();
added driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsIntegrationTest.java +92 −0
@@ -0,0 +1,92 @@
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.util.Collection;
19+import java.util.Collections;
20+import java.util.concurrent.LinkedBlockingQueue;
21+import java.util.concurrent.ThreadPoolExecutor;
22+import java.util.concurrent.TimeUnit;
23+
24+import org.testng.annotations.Test;
25+
26+import static org.assertj.core.api.Assertions.assertThat;
27+import static org.mockito.Matchers.any;
28+import static org.mockito.Mockito.atLeastOnce;
29+import static org.mockito.Mockito.reset;
30+import static org.mockito.Mockito.spy;
31+import static org.mockito.Mockito.verify;
32+
33+public class PoolingOptionsIntegrationTest extends CCMBridge.PerClassSingleNodeCluster {
34+ @Override
35+ protected Collection<String> getTableDefinitions() {
36+ return Collections.emptyList();
37+ }
38+
39+ /**
40+ * <p>
41+ * Validates that if a custom executor is provided via {@link PoolingOptions#setInitializationExecutor} that it
42+ * is used to create and tear down connections.
43+ * </p>
44+ *
45+ * @test_category connection:connection_pool
46+ * @expected_result executor is used and successfully able to connect and tear down connections.
47+ * @jira_ticket JAVA-692
48+ * @since 2.0.10, 2.1.6
49+ */
50+ @Test(groups = "short")
51+ public void should_be_able_to_use_custom_initialization_executor() {
52+ ThreadPoolExecutor executor = spy(new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
53+ new LinkedBlockingQueue<Runnable>()));
54+
55+ PoolingOptions poolingOptions = new PoolingOptions();
56+ poolingOptions.setInitializationExecutor(executor);
57+
58+ Cluster cluster = Cluster.builder()
59+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
60+ .withPoolingOptions(poolingOptions).build();
61+ try {
62+ cluster.init();
63+ // Ensure executor used.
64+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
65+
66+ // Reset invocation count.
67+ reset();
68+
69+ Session session = cluster.connect();
70+
71+ // Ensure executor used again to establish core connections.
72+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
73+
74+ // Expect core connections + control connection.
75+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(
76+ TestUtils.numberOfLocalCoreConnections(cluster) + 1);
77+
78+ reset();
79+
80+ session.close();
81+
82+ // Executor should have been used to close connections associated with the session.
83+ verify(executor, atLeastOnce()).execute(any(Runnable.class));
84+
85+ // Only the control connection should remain.
86+ assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(1);
87+ } finally {
88+ cluster.close();
89+ executor.shutdown();
90+ }
91+ }
92+}
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +70 −59
@@ -17,71 +17,82 @@
1717
1818 import org.testng.annotations.Test;
1919
20-import java.util.Collection;
21-import java.util.Collections;
22-import java.util.concurrent.*;
23-
2420 import static org.assertj.core.api.Assertions.assertThat;
25-import static org.mockito.Matchers.any;
26-import static org.mockito.Mockito.*;
27-
28-public class PoolingOptionsTest extends CCMBridge.PerClassSingleNodeCluster {
29- @Override
30- protected Collection<String> getTableDefinitions() {
31- return Collections.emptyList();
21+import static org.assertj.core.api.Assertions.fail;
22+
23+import static com.datastax.driver.core.HostDistance.LOCAL;
24+import static com.datastax.driver.core.HostDistance.REMOTE;
25+
26+public class PoolingOptionsTest {
27+
28+ @Test(groups = "unit")
29+ public void should_initialize_to_v2_defaults_if_v2_or_below() {
30+ PoolingOptions options = new PoolingOptions();
31+ options.setProtocolVersion(ProtocolVersion.V1);
32+
33+ assertThat(options.getCoreConnectionsPerHost(LOCAL)).isEqualTo(2);
34+ assertThat(options.getMaxConnectionsPerHost(LOCAL)).isEqualTo(8);
35+ assertThat(options.getCoreConnectionsPerHost(REMOTE)).isEqualTo(1);
36+ assertThat(options.getMaxConnectionsPerHost(REMOTE)).isEqualTo(2);
37+ assertThat(options.getNewConnectionThreshold(LOCAL)).isEqualTo(100);
38+ assertThat(options.getNewConnectionThreshold(REMOTE)).isEqualTo(100);
39+ assertThat(options.getMaxRequestsPerConnection(LOCAL)).isEqualTo(128);
40+ assertThat(options.getMaxRequestsPerConnection(REMOTE)).isEqualTo(128);
3241 }
3342
34- /**
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
44- */
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();
56- try {
57- cluster.init();
58- // Ensure executor used.
59- verify(executor, atLeastOnce()).execute(any(Runnable.class));
60-
61- // Reset invocation count.
62- reset();
63-
64- Session session = cluster.connect();
65-
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);
43+ @Test(groups = "unit")
44+ public void should_initialize_to_v3_defaults_if_v3_or_above() {
45+ PoolingOptions options = new PoolingOptions();
46+ options.setProtocolVersion(ProtocolVersion.V3);
47+
48+ assertThat(options.getCoreConnectionsPerHost(LOCAL)).isEqualTo(1);
49+ assertThat(options.getMaxConnectionsPerHost(LOCAL)).isEqualTo(1);
50+ assertThat(options.getCoreConnectionsPerHost(REMOTE)).isEqualTo(1);
51+ assertThat(options.getMaxConnectionsPerHost(REMOTE)).isEqualTo(1);
52+ assertThat(options.getNewConnectionThreshold(LOCAL)).isEqualTo(800);
53+ assertThat(options.getNewConnectionThreshold(REMOTE)).isEqualTo(200);
54+ assertThat(options.getMaxRequestsPerConnection(LOCAL)).isEqualTo(1024);
55+ assertThat(options.getMaxRequestsPerConnection(REMOTE)).isEqualTo(256);
56+ }
7257
73- reset();
58+ @Test(groups = "unit")
59+ public void should_enforce_invariants_once_protocol_version_known() {
60+ // OK for v2 (default max = 8)
61+ PoolingOptions options = new PoolingOptions().setCoreConnectionsPerHost(LOCAL, 3);
62+ options.setCoreConnectionsPerHost(LOCAL, 3);
63+ options.setProtocolVersion(ProtocolVersion.V2);
64+ assertThat(options.getCoreConnectionsPerHost(LOCAL)).isEqualTo(3);
65+ assertThat(options.getMaxConnectionsPerHost(LOCAL)).isEqualTo(8);
66+
67+ // KO for v3 (default max = 1)
68+ options = new PoolingOptions().setCoreConnectionsPerHost(LOCAL, 3);
69+ try {
70+ options.setProtocolVersion(ProtocolVersion.V3);
71+ fail("Expected an IllegalArgumentException");
72+ } catch (IllegalArgumentException e) {/*expected*/}
73+
74+ // OK for v3 (up to 32K stream ids)
75+ options = new PoolingOptions().setMaxRequestsPerConnection(LOCAL, 5000);
76+ options.setProtocolVersion(ProtocolVersion.V3);
77+ assertThat(options.getMaxRequestsPerConnection(LOCAL)).isEqualTo(5000);
78+
79+ // KO for v2 (up to 128)
80+ options = new PoolingOptions().setMaxRequestsPerConnection(LOCAL, 5000);
81+ try {
82+ options.setProtocolVersion(ProtocolVersion.V2);
83+ fail("Expected an IllegalArgumentException");
84+ } catch (IllegalArgumentException e) {/*expected*/}
85+ }
7486
75- session.close();
87+ @Test(groups = "unit")
88+ public void should_set_core_and_max_connections_simultaneously() {
89+ PoolingOptions options = new PoolingOptions();
90+ options.setProtocolVersion(ProtocolVersion.V2);
7691
77- // Executor should have been used to close connections associated with the session.
78- verify(executor, atLeastOnce()).execute(any(Runnable.class));
92+ options.setConnectionsPerHost(LOCAL, 10, 15);
7993
80- // Only the control connection should remain.
81- assertThat(cluster.getMetrics().getOpenConnections().getValue()).isEqualTo(1);
82- } finally {
83- cluster.close();
84- executor.shutdown();
85- }
94+ assertThat(options.getCoreConnectionsPerHost(LOCAL)).isEqualTo(10);
95+ assertThat(options.getMaxConnectionsPerHost(LOCAL)).isEqualTo(15);
8696 }
8797 }
98+
modified driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +1 −4
@@ -83,9 +83,6 @@
8383
8484 private Connection getSingleConnection(Session session) {
8585 HostConnectionPool pool = ((SessionManager)session).pools.values().iterator().next();
86- if (pool instanceof DynamicConnectionPool)
87- return ((DynamicConnectionPool)pool).connections.get(0);
88- else
89- return ((SingleConnectionPool)pool).connectionRef.get();
86+ return pool.connections.get(0);
9087 }
9188 }
modified driver-core/src/test/java/com/datastax/driver/core/SingleConnectionPoolTest.java +1 −1
@@ -41,7 +41,7 @@
4141 // Throttle to a very low value. Even a single thread can generate a higher throughput.
4242 final int maxRequests = 10;
4343 cluster.getConfiguration().getPoolingOptions()
44- .setMaxSimultaneousRequestsPerHostThreshold(HostDistance.LOCAL, maxRequests);
44+ .setMaxRequestsPerConnection(HostDistance.LOCAL, maxRequests);
4545
4646 // Track in flight requests in a dedicated thread every second
4747 final AtomicBoolean excessInflightQueriesSpotted = new AtomicBoolean(false);
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +1 −4
@@ -395,10 +395,7 @@
395395
396396 public static int numberOfLocalCoreConnections(Cluster cluster) {
397397 Configuration configuration = cluster.getConfiguration();
398- ProtocolVersion protocolVersion = configuration.getProtocolOptions().getProtocolVersionEnum();
399- return (protocolVersion.compareTo(ProtocolVersion.V3) < 0)
400- ? configuration.getPoolingOptions().getCoreConnectionsPerHost(HostDistance.LOCAL)
401- : 1;
398+ return configuration.getPoolingOptions().getCoreConnectionsPerHost(HostDistance.LOCAL);
402399 }
403400
404401 /**
modified driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +1 −1
@@ -78,7 +78,7 @@
7878 new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042)
7979 );
8080
81- PoolingOptions poolingOptions = new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 8);
81+ PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(HostDistance.LOCAL, 8, 8);
8282
8383 cluster = Cluster.builder()
8484 .addContactPointsWithPorts(nodes)
modified driver-examples/stress/src/main/java/com/datastax/driver/stress/Stress.java +1 −1
@@ -210,7 +210,7 @@
210210 : concurrency / maxRequestsPerConnection + 1;
211211
212212 PoolingOptions pools = new PoolingOptions();
213- pools.setMaxSimultaneousRequestsPerConnectionThreshold(HostDistance.LOCAL, concurrency);
213+ pools.setNewConnectionThreshold(HostDistance.LOCAL, concurrency);
214214 pools.setCoreConnectionsPerHost(HostDistance.LOCAL, maxConnections);
215215 pools.setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections);
216216 pools.setCoreConnectionsPerHost(HostDistance.REMOTE, maxConnections);
modified features/pooling/README.md +64 −61
@@ -23,19 +23,17 @@
2323 connections to each host. **For each `Session` object, there is one
2424 connection pool per connected host**.
2525
26-The number of connections and stream ids depends on the [native protocol
27-version](../native_protocol/):
28-
29-* **protocol v2 or below**: there are **128 stream ids per connection.**
30- The number of connections per pool is configurable (this will be
31- described in the next section).
32-* v3 or above: there are **up to 32768 stream ids per connection**, and
33- **1 connection per pool**.
26+The number of connections per pool is configurable (this will be
27+described in the next section). The number of stream ids depends on the
28+[native protocol version](../native_protocol/):
29+
30+* protocol v2 or below: 128 stream ids per connection.
31+* protocol v3 or above: up to 32768 stream ids per connection.
3432
3533 ```ditaa
36-+-------+1 n+-------+1 n+----+1 n/1+----------+1 128/32K+-------+
37-|Cluster+-----+Session+-----+Pool+-------+Connection+-----------+Request+
38-+-------+ +-------+ +----+ +----------+ +-------+
34++-------+1 n+-------+1 n+----+1 n+----------+1 128/32K+-------+
35+|Cluster+-----+Session+-----+Pool+-----+Connection+-----------+Request+
36++-------+ +-------+ +----+ +----------+ +-------+
3937 ```
4038
4139 ### Configuring the connection pool
@@ -62,7 +60,7 @@
6260 // customize options...
6361 ```
6462
65-#### Pool size (protocol v2 only)
63+#### Pool size
6664
6765 Connection pools have a variable size, which gets adjusted automatically
6866 depending on the current load. There will always be at least a *core*
@@ -79,36 +77,52 @@
7977 .setMaxConnectionsPerHost( HostDistance.REMOTE, 4);
8078 ```
8179
82-Note: the setters always enforce core <= max, which can get annoying
83-when you try to set both values at once.
84-[JAVA-662](https://datastax-oss.atlassian.net/browse/JAVA-662) will
85-address this issue.
86-
87-[PoolingOptions.setMaxSimultaneousRequestsPerConnectionThreshold][msrpct]
88-has a slightly misleading name: it does not limit the number of requests per
89-connection, but only determines the threshold that triggers the creation
90-of a new connection when the pool is not at its maximum capacity. In
91-general, you shouldn't have to change its default value.
92-
93-#### Number of simultaneous requests per host (protocol v3 only)
94-
95-Protocol v3 uses a single connection per host. While the number of
96-simultaneous requests can go up to 32768, it is limited by
97-[PoolingOptions.setMaxSimultaneousRequestsPerHostThreshold][msrpht]. The
98-goal of this option is to throttle the load that each client can
99-generate on the server. By default, it is set to 1024 for local hosts,
100-and 256 for remote hosts (this was chosen to match the capacity of a v2
101-pool with the default configuration).
102-
103-If your performance tests show that your cluster can handle a higher
104-load, you can raise this threshold:
80+For convenience, core and max can be set simultaneously:
81+
82+```java
83+poolingOptions
84+ .setConnectionsPerHost(HostDistance.LOCAL, 4, 10)
85+ .setConnectionsPerHost(HostDistance.REMOTE, 2, 4);
86+```
87+
88+The default settings are:
89+
90+* protocol v2:
91+ * `LOCAL` hosts: core = 2, max = 8
92+ * `REMOTE` hosts: core = 1, max = 2
93+* protocol v3:
94+ * `LOCAL` hosts: core = max = 1
95+ * `REMOTE` hosts: core = max = 1
96+
97+[PoolingOptions.setNewConnectionThreshold][nct] determines the threshold
98+that triggers the creation of a new connection when the pool is not at
99+its maximum capacity. In general, you shouldn't need to change its
100+default value.
101+
102+#### Simultaneous requests per connection
103+
104+[PoolingOptions.setMaxRequestsPerConnection][mrpc] allows you to
105+throttle the number of concurrent requests per connection.
106+
107+With protocol v2, there is no reason to throttle. It is set to 128 (the
108+max) and you should not change it.
109+
110+With protocol v3, it is set to 1024 for `LOCAL` hosts, and 256 for
111+`REMOTE` hosts. These low defaults were chosen so that the default
112+configuration for protocol v2 and v3 allow the same total number of
113+simultaneous requests (to avoid bad surprises when clients migrate from
114+v2 to v3). You can raise this threshold, or even set it to the max:
105115
106116 ```java
107117 poolingOptions
108- .setMaxSimultaneousRequestsPerHostThreshold(HostDistance.LOCAL, 20000)
109- .setMaxSimultaneousRequestsPerHostThreshold(HostDistance.REMOTE, 1000);
118+ .setMaxRequestsPerConnection(HostDistance.LOCAL, 32768)
119+ .setMaxRequestsPerConnection(HostDistance.REMOTE, 2000);
110120 ```
111121
122+Just keep in mind that high values will give clients more bandwidth and
123+therefore put more pressure on your cluster. This might require some
124+tuning, especially if you have many clients.
125+
112126 #### Heartbeat
113127
114128 If connections stay idle for too long, they might be dropped by
@@ -173,24 +187,11 @@
173187 ```java
174188 final LoadBalancingPolicy loadBalancingPolicy =
175189 cluster.getConfiguration().getPolicies().getLoadBalancingPolicy();
176-PoolingOptions poolingOptions = cluster.getConfiguration().getPoolingOptions();
177-ProtocolOptions protocolOptions = cluster.getConfiguration().getProtocolOptions();
178-
179-final Map<HostDistance, Integer> requestsPerConnection;
180-ProtocolVersion protocolVersion = protocolOptions.getProtocolVersionEnum();
181-if (protocolVersion == ProtocolVersion.V3) {
182- requestsPerConnection = ImmutableMap.of(
183- HostDistance.LOCAL,
184- poolingOptions.getMaxSimultaneousRequestsPerHostThreshold(HostDistance.LOCAL),
185- HostDistance.REMOTE,
186- poolingOptions.getMaxSimultaneousRequestsPerHostThreshold(HostDistance.REMOTE));
187-} else {
188- requestsPerConnection = ImmutableMap.of(
189- HostDistance.LOCAL, 128,
190- HostDistance.REMOTE, 128);
191-}
192-
193-ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);
190+final PoolingOptions poolingOptions =
191+cluster.getConfiguration().getPoolingOptions();
192+
193+ScheduledExecutorService scheduled =
194+Executors.newScheduledThreadPool(1);
194195 scheduled.scheduleAtFixedRate(new Runnable() {
195196 @Override
196197 public void run() {
@@ -199,9 +200,11 @@
199200 HostDistance distance = loadBalancingPolicy.distance(host);
200201 int connections = state.getOpenConnections(host);
201202 int inFlightQueries = state.getInFlightQueries(host);
202- System.out.printf("%s connections=%d current load=%d max load=%d%n",
203+ System.out.printf("%s connections=%d, current load=%d, max
204+load=%d%n",
203205 host, connections, inFlightQueries,
204- connections * requestsPerConnection.get(distance));
206+ connections *
207+poolingOptions.getMaxRequestsPerConnection(distance));
205208 }
206209 }
207210 }, 5, 5, TimeUnit.SECONDS);
@@ -213,8 +216,8 @@
213216
214217 If you find that the current load stays close or equal to the maximum
215218 load at all time, it's a sign that your connection pools are saturated
216-and you should raise the max connections per host (protocol v2) or max
217-requests per host (protocol v3).
219+and you should raise the max connections per host, or max requests per
220+connection (protocol v3).
218221
219222 If you're using protocol v2 and the load is often less than core * 128,
220223 your pools are underused and you could get away with less core
@@ -223,8 +226,8 @@
223226 [result_set_future]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSetFuture.html
224227 [pooling_options]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html
225228 [lbp]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/LoadBalancingPolicy.html
226-[msrpct]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setMaxSimultaneousRequestsPerConnectionThreshold(com.datastax.driver.core.HostDistance,%20int)
227-[msrpht]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setMaxSimultaneousRequestsPerHostThreshold(com.datastax.driver.core.HostDistance,%20int)
229+[nct]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold(com.datastax.driver.core.HostDistance,%20int)
230+[mrpc]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection(com.datastax.driver.core.HostDistance,%20int)
228231 [rtm]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis()
229232 [exec_async]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Session.html#executeAsync(com.datastax.driver.core.Statement)
230233 [ptm]:http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
modified upgrade_guide/README.md +15 −5
@@ -14,6 +14,17 @@
1414 In this case, trying another node has a chance of success.
1515 The previous behaviour was to always throw an exception.
1616
17+2. The following properties in `PoolingOptions` were renamed:
18+ * `MaxSimultaneousRequestsPerConnectionThreshold` to `NewConnectionThreshold`
19+ * `MaxSimultaneousRequestsPerHostThreshold` to `MaxRequestsPerConnection`
20+
21+ The old getters/setters were deprecated, but they delegate to the new
22+ ones.
23+
24+ Also, note that the connection pool for protocol v3 can now be configured to
25+ use multiple connections. See [this page](../features/pooling) for more
26+ information.
27+
1728
1829 ### 2.1.6
1930
@@ -341,8 +352,7 @@
341352 of data. In general paging should be transparent for the application (as in
342353 the example above), but the implementation provides a number of knobs to
343354 fine tune the behavior of that paging:
344-
345- * the size of each "page" can be set per-query (`Statement#setFetchSize()`)
346- * the `ResultSet` object provides 2 methods to check the state of paging
347- (`ResultSet#getAvailableWithoutFetching` and `ResultSet#isFullyFetched`)
348- as well as a mean to force the pre-fetching of the next page (`ResultSet#fetchMoreResults`).
355+ * the size of each "page" can be set per-query (`Statement#setFetchSize()`)
356+ * the `ResultSet` object provides 2 methods to check the state of paging
357+ (`ResultSet#getAvailableWithoutFetching` and `ResultSet#isFullyFetched`)
358+ as well as a mean to force the pre-fetching of the next page (`ResultSet#fetchMoreResults`).