Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changesetbc214054949d1d5b1ffeb5414a053563028178fb8620835b1c0e0c7641360a1f
Authorolim7t <omichallat+github@gmail.com> · 2014-10-02 21:55 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2014-10-02 21:56 +02:00
Parents79e97cbc6bb9, e968aa87642c

Browse the files at this changeset

8 files changed

modified driver-core/CHANGELOG.rst +2 −2
@@ -19,9 +19,9 @@
1919 Merged from 2.0 branch:
2020
2121 - [bug] Handle null pool in PooledConnection.release (JAVA-449)
22-- [bug] Prevent concurrent retries of the same query (JAVA-449)
2322 - [improvement] Defunct connection on request timeout (JAVA-425)
2423 - [improvement] Try next host when we get a SERVER_ERROR (JAVA-426)
24+- [bug] Handle race between query timeout and completion (JAVA-449, JAVA-460, JAVA-471)
2525
2626
2727 2.1.1:
@@ -89,9 +89,9 @@
8989 ------
9090
9191 - [bug] Handle null pool in PooledConnection.release (JAVA-449)
92-- [bug] Prevent concurrent retries of the same query (JAVA-449)
9392 - [improvement] Defunct connection on request timeout (JAVA-425)
9493 - [improvement] Try next host when we get a SERVER_ERROR (JAVA-426)
94+- [bug] Handle race between query timeout and completion (JAVA-449, JAVA-460, JAVA-471)
9595
9696
9797 2.0.6:
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +9 −3
@@ -358,21 +358,27 @@
358358
359359 // This is only called for internal calls, so don't bother with ExecutionInfo
360360 @Override
361- public void onSet(Connection connection, Message.Response response, long latency) {
361+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
362362 onSet(connection, response, null, null, latency);
363363 }
364364
365365 @Override
366- public void onException(Connection connection, Exception exception, long latency) {
366+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
367367 future.setException(exception);
368368 }
369369
370370 @Override
371- public void onTimeout(Connection connection, long latency) {
371+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
372372 // This won't be called directly since this will be wrapped by RequestHandler.
373373 throw new UnsupportedOperationException();
374374 }
375375
376+ @Override
377+ public int retryCount() {
378+ // This is only called for internal calls (i.e, when the callback is not wrapped in RequestHandler).
379+ // There is no retry logic in that case, so the value does not really matter.
380+ return 0;
381+ }
376382 }, statement);
377383
378384 return future;
modified driver-core/src/main/java/com/datastax/driver/core/BoundStatement.java +38 −8
@@ -50,6 +50,8 @@
5050 // we still want to avoid duplicating too much code so we wrap.
5151 final DataWrapper wrapper;
5252
53+ private ByteBuffer routingKey;
54+
5355 /**
5456 * Creates a new {@code BoundStatement} from the provided prepared
5557 * statement.
@@ -99,7 +101,11 @@
99101 *
100102 * @param name the name of the variable to check.
101103 * @return whether the first occurrence of variable {@code name} has been
104+<<<<<<< HEAD
102105 * bound.
106+=======
107+ * bound to a non-null value.
108+>>>>>>> 2.0
103109 *
104110 * @throws IllegalArgumentException if {@code name} is not a prepared
105111 * variable, that is if {@code !this.preparedStatement().variables().names().contains(name)}.
@@ -204,28 +210,52 @@
204210 return this;
205211 }
206212
213+ /**
214+ * Sets the routing key for this bound statement.
215+ * <p>
216+ * This is useful when the routing key can neither be set on the {@code PreparedStatement} this bound statement
217+ * was built from, nor automatically computed from bound variables. In particular, this is the case if the
218+ * partition key is composite and only some of its components are bound.
219+ *
220+ * @param routingKey the raw (binary) value to use as routing key.
221+ * @return this {@code BoundStatement} object.
222+ *
223+ * @see BoundStatement#getRoutingKey
224+ */
225+ public BoundStatement setRoutingKey(ByteBuffer routingKey) {
226+ this.routingKey = routingKey;
227+ return this;
228+ }
229+
207230 /**
208231 * The routing key for this bound query.
209232 * <p>
210233 * This method will return a non-{@code null} value if either of the following occur:
211234 * <ul>
212- * <li>All the columns composing the partition key are bound
213- * variables of this {@code BoundStatement}. The routing key will then be
214- * built using the values provided for these partition key columns.</li>
215- * <li>The routing key has been set through {@link PreparedStatement#setRoutingKey}
216- * for the {@code PreparedStatement} this statement has been built from.</li>
235+ * <li>The routing key has been set directly through {@link BoundStatement#setRoutingKey}.</li>
236+ * <li>The routing key has been set through {@link PreparedStatement#setRoutingKey} for the
237+ * {@code PreparedStatement} this statement has been built from.</li>
238+ * <li>All the columns composing the partition key are bound variables of this {@code BoundStatement}. The routing
239+ * key will then be built using the values provided for these partition key columns.</li>
217240 * </ul>
218241 * Otherwise, {@code null} is returned.
219242 * <p>
220- * Note that if the routing key has been set through {@link PreparedStatement#setRoutingKey},
221- * that latter value takes precedence even if the partition key is part of the bound variables.
243+ *
244+ * Note that if the routing key has been set through {@link BoundStatement#setRoutingKey}, then that takes
245+ * precedence. If the routing key has been set through {@link PreparedStatement#setRoutingKey} then that is used
246+ * next. If neither of those are set then it is computed.
222247 *
223248 * @return the routing key for this statement or {@code null}.
224249 */
225250 @Override
226251 public ByteBuffer getRoutingKey() {
227- if (statement.getRoutingKey() != null)
252+ if (this.routingKey != null) {
253+ return this.routingKey;
254+ }
255+
256+ if (statement.getRoutingKey() != null) {
228257 return statement.getRoutingKey();
258+ }
229259
230260 int[] rkIndexes = statement.getPreparedId().routingKeyIndexes;
231261 if (rkIndexes != null) {
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +22 −12
@@ -16,7 +16,6 @@
1616 package com.datastax.driver.core;
1717
1818 import javax.net.ssl.SSLEngine;
19-import java.net.InetAddress;
2019 import java.net.InetSocketAddress;
2120 import java.util.Iterator;
2221 import java.util.concurrent.*;
@@ -388,7 +387,7 @@
388387 } else {
389388 ce = new TransportException(address, "Error writing", writeFuture.getCause());
390389 }
391- handler.callback.onException(Connection.this, defunct(ce), System.nanoTime() - handler.startTime);
390+ handler.callback.onException(Connection.this, defunct(ce), System.nanoTime() - handler.startTime, handler.retryCount);
392391 } else {
393392 logger.trace("{} request sent successfully", Connection.this);
394393 }
@@ -659,7 +658,7 @@
659658 return;
660659 }
661660 handler.cancelTimeout();
662- handler.callback.onSet(Connection.this, response, System.nanoTime() - handler.startTime);
661+ handler.callback.onSet(Connection.this, response, System.nanoTime() - handler.startTime, handler.retryCount);
663662
664663 // If we happen to be closed and we're the last outstanding request, we need to terminate the connection
665664 // (note: this is racy as the signaling can be called more than once, but that's not a problem)
@@ -698,7 +697,7 @@
698697 {
699698 ResponseHandler handler = iter.next();
700699 handler.cancelTimeout();
701- handler.callback.onException(Connection.this, ce, System.nanoTime() - handler.startTime);
700+ handler.callback.onException(Connection.this, ce, System.nanoTime() - handler.startTime, handler.retryCount);
702701 iter.remove();
703702 }
704703 }
@@ -765,19 +764,25 @@
765764 return request;
766765 }
767766
767+ @Override
768+ public int retryCount() {
769+ // This is ignored, as there is no retry logic in this class
770+ return 0;
771+ }
772+
768773 @Override
769774 public void onSet(Connection connection, Message.Response response, ExecutionInfo info, Statement statement, long latency) {
770- onSet(connection, response, latency);
775+ onSet(connection, response, latency, 0);
771776 }
772777
773778 @Override
774- public void onSet(Connection connection, Message.Response response, long latency) {
779+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
775780 this.address = connection.address;
776781 super.set(response);
777782 }
778783
779784 @Override
780- public void onException(Connection connection, Exception exception, long latency) {
785+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
781786 // If all nodes are down, we will get a null connection here. This is fine, if we have
782787 // an exception, consumers shouldn't assume the address is not null.
783788 if (connection != null)
@@ -786,10 +791,11 @@
786791 }
787792
788793 @Override
789- public void onTimeout(Connection connection, long latency) {
794+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
790795 assert connection != null; // We always timeout on a specific connection, so this shouldn't be null
791796 this.address = connection.address;
792797 super.setException(new ConnectionException(connection.address, "Operation timed out"));
798+ return true;
793799 }
794800
795801 public InetSocketAddress getAddress() {
@@ -799,9 +805,10 @@
799805
800806 interface ResponseCallback {
801807 public Message.Request request();
802- public void onSet(Connection connection, Message.Response response, long latency);
803- public void onException(Connection connection, Exception exception, long latency);
804- public void onTimeout(Connection connection, long latency);
808+ public int retryCount();
809+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount);
810+ public void onException(Connection connection, Exception exception, long latency, int retryCount);
811+ public boolean onTimeout(Connection connection, long latency, int retryCount);
805812 }
806813
807814 static class ResponseHandler {
@@ -809,6 +816,7 @@
809816 public final Connection connection;
810817 public final int streamId;
811818 public final ResponseCallback callback;
819+ public final int retryCount;
812820
813821 private final Timeout timeout;
814822 private final long startTime;
@@ -817,6 +825,7 @@
817825 this.connection = connection;
818826 this.streamId = connection.dispatcher.streamIdHandler.next();
819827 this.callback = callback;
828+ this.retryCount = callback.retryCount();
820829
821830 long timeoutMs = connection.factory.getReadTimeoutMillis();
822831 this.timeout = timeoutMs <= 0 ? null : connection.factory.timer.newTimeout(onTimeoutTask(), timeoutMs, TimeUnit.MILLISECONDS);
@@ -843,7 +852,8 @@
843852 return new TimerTask() {
844853 @Override
845854 public void run(Timeout timeout) {
846- callback.onTimeout(connection, System.nanoTime() - startTime);
855+ if (callback.onTimeout(connection, System.nanoTime() - startTime, retryCount))
856+ cancelHandler();
847857 }
848858 };
849859 }
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +12 −4
@@ -122,22 +122,23 @@
122122 }
123123
124124 @Override
125- public void onSet(Connection connection, Message.Response response, long latency) {
125+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
126126 // This is only called for internal calls (i.e, when the callback is not wrapped in ResponseHandler),
127127 // so don't bother with ExecutionInfo.
128128 onSet(connection, response, null, null, latency);
129129 }
130130
131131 @Override
132- public void onException(Connection connection, Exception exception, long latency) {
132+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
133133 setException(exception);
134134 }
135135
136136 @Override
137- public void onTimeout(Connection connection, long latency) {
138- // This is only called for internal calls (i.e, when the callback is not wrapped in ResponseHandler).
137+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
138+ // This is only called for internal calls (i.e, when the future is not wrapped in RequestHandler).
139139 // So just set an exception for the final result, which should be handled correctly by said internal call.
140140 setException(new ConnectionException(connection.address, "Operation timed out"));
141+ return true;
141142 }
142143
143144 // We sometimes need (in the driver) to set the future from outside this class,
@@ -259,4 +260,11 @@
259260 else
260261 throw new DriverInternalError("Unexpected exception thrown", e.getCause());
261262 }
263+
264+ @Override
265+ public int retryCount() {
266+ // This is only called for internal calls (i.e, when the future is not wrapped in RequestHandler).
267+ // There is no retry logic in that case, so the value does not really matter.
268+ return 0;
269+ }
262270 }
modified driver-core/src/main/java/com/datastax/driver/core/PreparedStatement.java +5 −0
@@ -98,11 +98,16 @@
9898 * <p>
9999 * Note that if the partition key is part of the prepared variables, the
100100 * routing key will be automatically computed once those variables are bound.
101+ * <p>
102+ * If the partition key is neither fixed nor part of the prepared variables (e.g.
103+ * a composite partition key where only some of the components are bound), the
104+ * routing key can also be set on each bound statement.
101105 *
102106 * @param routingKey the raw (binary) value to use as routing key.
103107 * @return this {@code PreparedStatement} object.
104108 *
105109 * @see Statement#getRoutingKey
110+ * @see BoundStatement#getRoutingKey
106111 */
107112 public PreparedStatement setRoutingKey(ByteBuffer routingKey);
108113
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +119 −51
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetAddress;
1918 import java.net.InetSocketAddress;
2019 import java.nio.ByteBuffer;
2120 import java.util.ArrayList;
@@ -24,9 +23,9 @@
2423 import java.util.Iterator;
2524 import java.util.List;
2625 import java.util.Map;
27-import java.util.concurrent.*;
28-import java.util.concurrent.locks.Lock;
29-import java.util.concurrent.locks.ReentrantLock;
26+import java.util.concurrent.TimeUnit;
27+import java.util.concurrent.TimeoutException;
28+import java.util.concurrent.atomic.AtomicReference;
3029
3130 import com.codahale.metrics.Timer;
3231 import org.slf4j.Logger;
@@ -39,7 +38,6 @@
3938 import com.datastax.driver.core.exceptions.UnavailableException;
4039 import com.datastax.driver.core.exceptions.WriteTimeoutException;
4140 import com.datastax.driver.core.policies.*;
42-import com.datastax.driver.core.policies.RetryPolicy.RetryDecision;
4341 import com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type;
4442
4543 /**
@@ -47,7 +45,6 @@
4745 * unavailable/timeout.
4846 */
4947 class RequestHandler implements Connection.ResponseCallback {
50-
5148 private static final Logger logger = LoggerFactory.getLogger(RequestHandler.class);
5249
5350 private final SessionManager manager;
@@ -58,10 +55,8 @@
5855 private volatile Host current;
5956 private volatile List<Host> triedHosts;
6057 private volatile HostConnectionPool currentPool;
58+ private final AtomicReference<QueryState> queryStateRef;
6159
62- // Note that we know that queryRetries can only be incremented by one writer at a time so a
63- // volatile is good enough.
64- private volatile int queryRetries;
6560 private volatile ConsistencyLevel retryConsistencyLevel;
6661
6762 private volatile Map<InetSocketAddress, Throwable> errors;
@@ -72,10 +67,6 @@
7267 private final Timer.Context timerContext;
7368 private final long startTime;
7469
75- // Tracks whether there is a retry already in progress
76- private final Lock retryLock = new ReentrantLock();
77- private Future<?> currentRetry; // guarded by retryLock
78-
7970 public RequestHandler(SessionManager manager, Callback callback, Statement statement) {
8071 this.manager = manager;
8172 this.callback = callback;
@@ -84,6 +75,7 @@
8475
8576 this.queryPlan = manager.loadBalancingPolicy().newQueryPlan(manager.poolsState.keyspace, statement);
8677 this.statement = statement;
78+ this.queryStateRef = new AtomicReference<QueryState>(QueryState.INITIAL);
8779
8880 this.timerContext = metricsEnabled()
8981 ? metrics().getRequestsTimer().time()
@@ -167,34 +159,26 @@
167159 }
168160
169161 private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) {
170- try {
171- // We lock to prevent two retries from launching concurrently
172- retryLock.lock();
162+ queryStateRef.set(queryStateRef.get().startNext());
173163
174- if (currentRetry != null && !currentRetry.isDone())
175- return;
164+ final Host h = current;
165+ this.retryConsistencyLevel = newConsistencyLevel;
176166
177- final Host h = current;
178- this.retryConsistencyLevel = newConsistencyLevel;
179-
180- // We should not retry on the current thread as this will be an IO thread.
181- currentRetry = manager.executor().submit(new Runnable() {
182- @Override
183- public void run() {
184- try {
185- if (retryCurrent) {
186- if (query(h))
187- return;
188- }
189- sendRequest();
190- } catch (Exception e) {
191- setFinalException(null, new DriverInternalError("Unexpected exception while retrying query", e));
167+ // We should not retry on the current thread as this will be an IO thread.
168+ manager.executor().execute(new Runnable() {
169+ @Override
170+ public void run() {
171+ try {
172+ if (retryCurrent) {
173+ if (query(h))
174+ return;
192175 }
176+ sendRequest();
177+ } catch (Exception e) {
178+ setFinalException(null, new DriverInternalError("Unexpected exception while retrying query", e));
193179 }
194- });
195- } finally {
196- retryLock.unlock();
197- }
180+ }
181+ });
198182 }
199183
200184 public void cancel() {
@@ -261,7 +245,7 @@
261245 info = info.withAchievedConsistency(retryConsistencyLevel);
262246 callback.onSet(connection, response, info, statement, System.nanoTime() - startTime);
263247 } catch (Exception e) {
264- callback.onException(connection, new DriverInternalError("Unexpected exception while setting final result from " + response, e), System.nanoTime() - startTime);
248+ callback.onException(connection, new DriverInternalError("Unexpected exception while setting final result from " + response, e), System.nanoTime() - startTime, retryCount());
265249 }
266250 }
267251
@@ -270,12 +254,20 @@
270254 if (timerContext != null)
271255 timerContext.stop();
272256 } finally {
273- callback.onException(connection, exception, System.nanoTime() - startTime);
257+ callback.onException(connection, exception, System.nanoTime() - startTime, retryCount());
274258 }
275259 }
276260
277261 @Override
278- public void onSet(Connection connection, Message.Response response, long latency) {
262+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
263+ QueryState queryState = queryStateRef.get();
264+ if (!queryState.isInProgressAt(retryCount) ||
265+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
266+ logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
267+ retryCount, queryState, queryStateRef.get());
268+ return;
269+ }
270+
279271 Host queriedHost = current;
280272 try {
281273 if (connection instanceof PooledConnection)
@@ -303,7 +295,7 @@
303295 rte.getRequiredAcknowledgements(),
304296 rte.getReceivedAcknowledgements(),
305297 rte.wasDataRetrieved(),
306- queryRetries);
298+ retryCount);
307299
308300 if (metricsEnabled()) {
309301 if (retry.getType() == Type.RETRY)
@@ -323,7 +315,7 @@
323315 wte.getWriteType(),
324316 wte.getRequiredAcknowledgements(),
325317 wte.getReceivedAcknowledgements(),
326- queryRetries);
318+ retryCount);
327319
328320 if (metricsEnabled()) {
329321 if (retry.getType() == Type.RETRY)
@@ -342,7 +334,7 @@
342334 ue.getConsistencyLevel(),
343335 ue.getRequiredReplicas(),
344336 ue.getAliveReplicas(),
345- queryRetries);
337+ retryCount);
346338
347339 if (metricsEnabled()) {
348340 if (retry.getType() == Type.RETRY)
@@ -403,6 +395,7 @@
403395 connection.setKeyspace(prepareKeyspace);
404396 }
405397
398+ queryStateRef.set(queryStateRef.get().startNext());
406399 try {
407400 connection.write(prepareAndRetry(toPrepare.getQueryString()));
408401 } finally {
@@ -426,9 +419,8 @@
426419 else {
427420 switch (retry.getType()) {
428421 case RETRY:
429- ++queryRetries;
430422 if (logger.isDebugEnabled())
431- logger.debug("Doing retry {} for query {} at consistency {}", queryRetries, statement, retry.getRetryConsistencyLevel());
423+ logger.debug("Doing retry {} for query {} at consistency {}", retryCount, statement, retry.getRetryConsistencyLevel());
432424 if (metricsEnabled())
433425 metrics().getErrorMetrics().getRetries().inc();
434426 retry(true, retry.getRetryConsistencyLevel());
@@ -465,7 +457,20 @@
465457 }
466458
467459 @Override
468- public void onSet(Connection connection, Message.Response response, long latency) {
460+ public int retryCount() {
461+ return RequestHandler.this.retryCount();
462+ }
463+
464+ @Override
465+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
466+ QueryState queryState = queryStateRef.get();
467+ if (!queryState.isInProgressAt(retryCount) ||
468+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
469+ logger.debug("onSet triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
470+ retryCount, queryState, queryStateRef.get());
471+ return;
472+ }
473+
469474 // TODO should we check the response ?
470475 switch (response.type) {
471476 case RESULT:
@@ -491,20 +496,35 @@
491496 }
492497
493498 @Override
494- public void onException(Connection connection, Exception exception, long latency) {
495- RequestHandler.this.onException(connection, exception, latency);
499+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
500+ RequestHandler.this.onException(connection, exception, latency, retryCount);
496501 }
497502
498503 @Override
499- public void onTimeout(Connection connection, long latency) {
504+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
505+ QueryState queryState = queryStateRef.get();
506+ if (!queryState.isInProgressAt(retryCount) ||
507+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
508+ logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
509+ retryCount, queryState, queryStateRef.get());
510+ return false;
511+ }
500512 logError(connection.address, new DriverException("Timeout waiting for response to prepare message"));
501513 retry(false, null);
514+ return true;
502515 }
503516 };
504517 }
505518
506519 @Override
507- public void onException(Connection connection, Exception exception, long latency) {
520+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
521+ QueryState queryState = queryStateRef.get();
522+ if (!queryState.isInProgressAt(retryCount) ||
523+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
524+ logger.debug("onException triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
525+ retryCount, queryState, queryStateRef.get());
526+ return;
527+ }
508528
509529 Host queriedHost = current;
510530 try {
@@ -530,7 +550,15 @@
530550 }
531551
532552 @Override
533- public void onTimeout(Connection connection, long latency) {
553+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
554+ QueryState queryState = queryStateRef.get();
555+ if (!queryState.isInProgressAt(retryCount) ||
556+ !queryStateRef.compareAndSet(queryState, queryState.complete())) {
557+ logger.debug("onTimeout triggered but the response was completed by another thread, cancelling (retryCount = {}, queryState = {}, queryStateRef = {})",
558+ retryCount, queryState, queryStateRef.get());
559+ return false;
560+ }
561+
534562 Host queriedHost = current;
535563 try {
536564 // If a query times out, we consider that the host is unstable, so we defunct
@@ -547,10 +575,50 @@
547575 if (queriedHost != null)
548576 manager.cluster.manager.reportLatency(queriedHost, latency);
549577 }
578+ return true;
579+ }
580+
581+ @Override
582+ public int retryCount() {
583+ return queryStateRef.get().retryCount;
550584 }
551585
552586 interface Callback extends Connection.ResponseCallback {
553587 public void onSet(Connection connection, Message.Response response, ExecutionInfo info, Statement statement, long latency);
554588 public void register(RequestHandler handler);
555589 }
590+
591+ // This is used to prevent races between request completion (either success or error) and timeout.
592+ // A retry is in progress once we have written the request to the connection and until we get back a response or a timeout.
593+ // The count increments on each retry.
594+ static class QueryState {
595+ static QueryState INITIAL = new QueryState(0, true);
596+
597+ final int retryCount;
598+ final boolean inProgress;
599+
600+ private QueryState(int count, boolean inProgress) {
601+ this.retryCount = count;
602+ this.inProgress = inProgress;
603+ }
604+
605+ boolean isInProgressAt(int retryCount) {
606+ return inProgress && this.retryCount == retryCount;
607+ }
608+
609+ QueryState complete() {
610+ assert inProgress;
611+ return new QueryState(retryCount, false);
612+ }
613+
614+ QueryState startNext() {
615+ assert !inProgress;
616+ return new QueryState(retryCount + 1, true);
617+ }
618+
619+ @Override
620+ public String toString() {
621+ return String.format("QueryState(count=%d, inProgress=%s)", retryCount, inProgress);
622+ }
623+ }
556624 }
modified pom.xml +1 −0
@@ -17,6 +17,7 @@
1717 <groupId>org.sonatype.oss</groupId>
1818 <artifactId>oss-parent</artifactId>
1919 <version>7</version>
20+ <relativePath></relativePath>
2021 </parent>
2122
2223 <groupId>com.datastax.cassandra</groupId>