Elffuss BraidHub

kikocis/java-driver public

Change AbstractReconnectionHandler to yield to a previously running handler.

Also, expose a single Future in currentAttempt instead of switching in
the Futures from the executor. This makes it easier for clients to test
whether a handler is running at a given time.
Changesetc8289a3ecdadc0bfa926bf6d85d6f379185693b0f15878d45ca4213eeac05ec8
Authorolim7t <omichallat+github@gmail.com> · 2014-10-12 17:13 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2014-10-12 18:59 +02:00
Parentsa6ca982a760c

Browse the files at this changeset

5 files changed

modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +56 −39
@@ -15,13 +15,12 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.concurrent.RejectedExecutionException;
19-import java.util.concurrent.ScheduledExecutorService;
20-import java.util.concurrent.ScheduledFuture;
21-import java.util.concurrent.TimeUnit;
18+import java.util.concurrent.*;
2219 import java.util.concurrent.atomic.AtomicReference;
2320
2421 import com.google.common.util.concurrent.Uninterruptibles;
22+
23+import com.google.common.util.concurrent.AbstractFuture;
2524 import org.slf4j.Logger;
2625 import org.slf4j.LoggerFactory;
2726
@@ -34,12 +33,16 @@
3433
3534 private final ScheduledExecutorService executor;
3635 private final ReconnectionPolicy.ReconnectionSchedule schedule;
37- private final AtomicReference<ScheduledFuture<?>> currentAttempt;
36+ /**
37+ * The future that is exposed to clients, representing completion of the current active handler
38+ */
39+ private final AtomicReference<Future<?>> currentAttempt;
40+
41+ private final HandlerFuture handlerFuture = new HandlerFuture();
3842
39- private volatile boolean readyForNext;
40- private volatile ScheduledFuture<?> localFuture;
43+ private volatile boolean isActive;
4144
42- public AbstractReconnectionHandler(ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<ScheduledFuture<?>> currentAttempt) {
45+ public AbstractReconnectionHandler(ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<Future<?>> currentAttempt) {
4346 this.executor = executor;
4447 this.schedule = schedule;
4548 this.currentAttempt = currentAttempt;
@@ -60,18 +63,21 @@
6063 long firstDelay = schedule.nextDelayMs();
6164 logger.debug("First reconnection scheduled in {}ms", firstDelay);
6265 try {
63- localFuture = executor.schedule(this, firstDelay, TimeUnit.MILLISECONDS);
66+ handlerFuture.nextTry = executor.schedule(this, firstDelay, TimeUnit.MILLISECONDS);
6467
65- // If there a previous task, cancel it, so only one reconnection handler runs.
6668 while (true) {
67- ScheduledFuture<?> previous = currentAttempt.get();
68- if (currentAttempt.compareAndSet(previous, localFuture)) {
69- if (previous != null)
70- previous.cancel(false);
69+ Future<?> previous = currentAttempt.get();
70+ if (previous != null && !previous.isCancelled()) {
71+ logger.debug("Found another already active handler, cancelling");
72+ handlerFuture.cancel(false);
73+ return;
74+ }
75+ if (currentAttempt.compareAndSet(previous, handlerFuture)) {
76+ logger.debug("Becoming the active handler");
7177 break;
7278 }
7379 }
74- readyForNext = true;
80+ isActive = true;
7581 } catch (RejectedExecutionException e) {
7682 // The executor has been shutdown, fair enough, just ignore
7783 logger.debug("Aborting reconnection handling since the cluster is shutting down");
@@ -80,23 +86,26 @@
8086
8187 @Override
8288 public void run() {
83- // We shouldn't arrive here if the future is cancelled but better safe than sorry
84- if (localFuture.isCancelled())
89+ if (handlerFuture.isCancelled()) {
90+ logger.debug("Got cancelled, stopping");
8591 return;
92+ }
8693
87- // Don't run before ready, otherwise our cancel business might end up removing all connection attempts.
88- while (!readyForNext)
94+ // Just make sure we don't start the first try too fast, in case we find out we need to cancel ourselves in start()
95+ while (!isActive)
8996 Uninterruptibles.sleepUninterruptibly(5, TimeUnit.MILLISECONDS);
9097
9198 try {
9299 onReconnection(tryReconnect());
93- currentAttempt.compareAndSet(localFuture, null);
100+ handlerFuture.markAsDone();
101+ currentAttempt.compareAndSet(handlerFuture, null);
102+ logger.debug("Reconnection successful, cleared the future");
94103 } catch (ConnectionException e) {
95104 long nextDelay = schedule.nextDelayMs();
96105 if (onConnectionException(e, nextDelay))
97106 reschedule(nextDelay);
98107 else
99- currentAttempt.compareAndSet(localFuture, null);
108+ currentAttempt.compareAndSet(handlerFuture, null);
100109 } catch (AuthenticationException e) {
101110 logger.error(e.getMessage());
102111 long nextDelay = schedule.nextDelayMs();
@@ -104,7 +113,7 @@
104113 reschedule(nextDelay);
105114 } else {
106115 logger.error("Retry against {} have been suspended. It won't be retried unless the node is restarted.", e.getHost());
107- currentAttempt.compareAndSet(localFuture, null);
116+ currentAttempt.compareAndSet(handlerFuture, null);
108117 }
109118 } catch (InterruptedException e) {
110119 // If interrupted, skip this attempt but still skip scheduling reconnections
@@ -117,7 +126,7 @@
117126 reschedule(nextDelay);
118127 } else {
119128 logger.error("Retry against {} have been suspended. It won't be retried unless the node is restarted.", e.address);
120- currentAttempt.compareAndSet(localFuture, null);
129+ currentAttempt.compareAndSet(handlerFuture, null);
121130 }
122131 } catch (ClusterNameMismatchException e) {
123132 logger.error(e.getMessage());
@@ -126,37 +135,45 @@
126135 reschedule(nextDelay);
127136 } else {
128137 logger.error("Retry against {} have been suspended. It won't be retried unless the node is restarted.", e.address);
129- currentAttempt.compareAndSet(localFuture, null);
138+ currentAttempt.compareAndSet(handlerFuture, null);
130139 }
131140 } catch (Exception e) {
132141 long nextDelay = schedule.nextDelayMs();
133142 if (onUnknownException(e, nextDelay))
134143 reschedule(nextDelay);
135144 else
136- currentAttempt.compareAndSet(localFuture, null);
145+ currentAttempt.compareAndSet(handlerFuture, null);
137146 }
138147 }
139148
140149 private void reschedule(long nextDelay) {
141150 // If we got cancelled during the failed reconnection attempt that lead here, don't reschedule
142- if (localFuture.isCancelled()) {
143- currentAttempt.compareAndSet(localFuture, null);
151+ if (handlerFuture.isCancelled()) {
152+ currentAttempt.compareAndSet(handlerFuture, null);
144153 return;
145154 }
146155
147- readyForNext = false;
148- ScheduledFuture<?> newFuture = executor.schedule(this, nextDelay, TimeUnit.MILLISECONDS);
149- assert localFuture != null;
150- // If it's not our future the current one, then we've been canceled
151- if (!currentAttempt.compareAndSet(localFuture, newFuture)) {
152- newFuture.cancel(false);
156+ handlerFuture.nextTry = executor.schedule(this, nextDelay, TimeUnit.MILLISECONDS);
157+ }
158+
159+ // The future that the handler exposes to its clients via currentAttempt
160+ private static class HandlerFuture extends AbstractFuture<Void> {
161+ // A future representing completion of the next task submitted to the executor
162+ volatile ScheduledFuture<?> nextTry;
163+
164+ @Override
165+ public boolean cancel(boolean mayInterruptIfRunning) {
166+ // This is a check-then-act, so we may race with the scheduling of the first try, but in that case
167+ // we'll re-check for cancellation when this first try starts running
168+ if (nextTry != null) {
169+ nextTry.cancel(mayInterruptIfRunning);
170+ }
171+
172+ return super.cancel(mayInterruptIfRunning);
153173 }
154- // Check one last time is the previous future was cancelled (there is still a race if a client
155- // held on a reference to that future long after retrieving it from the AtomicReference)
156- if (localFuture.isCancelled()) {
157- newFuture.cancel(false);
174+
175+ void markAsDone() {
176+ super.set(null);
158177 }
159- localFuture = newFuture;
160- readyForNext = true;
161178 }
162179 }
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +1 −1
@@ -1311,7 +1311,7 @@
13111311 }
13121312
13131313 // If there is a reconnection attempt scheduled for that node, cancel it
1314- ScheduledFuture<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
1314+ Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
13151315 if (scheduledAttempt != null) {
13161316 logger.debug("Cancelling reconnection attempt since node is UP");
13171317 scheduledAttempt.cancel(false);
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +2 −2
@@ -20,7 +20,7 @@
2020 import java.net.UnknownHostException;
2121 import java.util.*;
2222 import java.util.concurrent.ExecutionException;
23-import java.util.concurrent.ScheduledFuture;
23+import java.util.concurrent.Future;
2424 import java.util.concurrent.TimeUnit;
2525 import java.util.concurrent.atomic.AtomicReference;
2626
@@ -63,7 +63,7 @@
6363
6464 private final Cluster.Manager cluster;
6565
66- private final AtomicReference<ScheduledFuture<?>> reconnectionAttempt = new AtomicReference<ScheduledFuture<?>>();
66+ private final AtomicReference<Future<?>> reconnectionAttempt = new AtomicReference<Future<?>>();
6767
6868 private volatile boolean isShutdown;
6969
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +2 −2
@@ -17,7 +17,7 @@
1717
1818 import java.net.InetAddress;
1919 import java.net.InetSocketAddress;
20-import java.util.concurrent.ScheduledFuture;
20+import java.util.concurrent.Future;
2121 import java.util.concurrent.atomic.AtomicReference;
2222
2323 import com.google.common.collect.ImmutableList;
@@ -47,7 +47,7 @@
4747 final AtomicReference<ListenableFuture<?>> initialReconnectionAttempt = new AtomicReference<ListenableFuture<?>>(Futures.immediateFuture(null));
4848
4949 // Tracks later reconnection attempts to that host so we avoid adding multiple tasks.
50- final AtomicReference<ScheduledFuture<?>> reconnectionAttempt = new AtomicReference<ScheduledFuture<?>>();
50+ final AtomicReference<Future<?>> reconnectionAttempt = new AtomicReference<Future<?>>();
5151
5252 final ExecutionInfo defaultExecutionInfo;
5353
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java +43 −11
@@ -4,12 +4,14 @@
44 import java.util.concurrent.*;
55 import java.util.concurrent.atomic.AtomicReference;
66
7-import com.google.common.util.concurrent.Runnables;
7+import com.google.common.util.concurrent.Futures;
8+import com.google.common.util.concurrent.SettableFuture;
89 import org.slf4j.Logger;
910 import org.slf4j.LoggerFactory;
1011 import org.testng.annotations.AfterMethod;
1112 import org.testng.annotations.BeforeMethod;
1213 import org.testng.annotations.Test;
14+
1315 import static org.assertj.core.api.Assertions.assertThat;
1416 import static org.testng.Assert.fail;
1517
@@ -22,7 +24,7 @@
2224 ScheduledExecutorService executor;
2325 MockReconnectionSchedule schedule;
2426 MockReconnectionWork work;
25- final AtomicReference<ScheduledFuture<?>> future = new AtomicReference<ScheduledFuture<?>>();
27+ final AtomicReference<Future<?>> future = new AtomicReference<Future<?>>();
2628 AbstractReconnectionHandler handler;
2729
2830 @BeforeMethod(groups = "unit")
@@ -106,9 +108,7 @@
106108
107109 assertThat(work.success).isFalse();
108110 assertThat(work.tries).isEqualTo(0);
109- // This is not a feature but is interesting to take note of (meaning that a non-null future
110- // does not necessarily mean that a handler is running):
111- assertThat(future.get()).isNotNull();
111+ assertThat(future.get().isCancelled()).isTrue();
112112 }
113113
114114 @Test(groups = "unit")
@@ -156,24 +156,56 @@
156156 assertThat(work.tries).isEqualTo(1);
157157 }
158158
159+ @Test(groups = "unit")
160+ public void should_yield_to_another_running_handler() {
161+ // Set an uncompleted future, representing a running handler
162+ future.set(SettableFuture.create());
163+
164+ handler.start();
165+
166+ // Increase the delay to make sure that the first attempt does not start before the check
167+ // for cancellation (which would require calling work.tick())
168+ schedule.delay = 5000;
169+ schedule.tick();
170+
171+ waitForCompletion();
172+
173+ assertThat(work.success).isFalse();
174+ }
175+
159176 /**
160- * This is how the class currently works, but wouldn't it be better to stop and let the other task run?
177+ * Note: a handler that succeeds immediately resets the future to null, so there is a very small window of opportunity
178+ * for this scenario. Therefore we consider that if we find a completed future, the connection was successfully
179+ * re-established a few milliseconds ago, so we don't start another attempt.
161180 */
162181 @Test(groups = "unit")
163- public void should_cancel_previous_task() {
164- // Schedule a dummy task just to have a future
165- ScheduledFuture<?> previousFuture = executor.schedule(Runnables.doNothing(), 1, TimeUnit.HOURS);
166- future.set(previousFuture);
182+ public void should_yield_to_another_handler_that_just_succeeded() {
183+ future.set(Futures.immediateCheckedFuture(null));
167184
168185 handler.start();
169186
170- assertThat(previousFuture.isCancelled()).isTrue();
187+ schedule.tick();
188+
189+ waitForCompletion();
190+
191+ assertThat(work.success).isFalse();
192+ }
193+
194+ @Test(groups = "unit")
195+ public void should_run_if_another_handler_was_cancelled() {
196+ future.set(Futures.immediateCancelledFuture());
197+
198+ handler.start();
171199
172200 schedule.tick();
173201 work.nextReconnect = ReconnectBehavior.SUCCEED;
174202 work.tick();
175203
176204 waitForCompletion();
205+
206+ assertThat(work.success).isTrue();
207+ assertThat(work.tries).isEqualTo(1);
208+ assertThat(future.get()).isNull();
177209 }
178210
179211 /**