Elffuss BraidHub

kikocis/java-driver public

Merge pull request #427 from datastax/java822

Improve asynchronous API (JAVA-821, JAVA-822)
Changeset6d032b5eb9c1de7db0ff589316dd6bd2f8955b9c7afc9dd0cc410a42650159dc
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-08-28 11:37 +02:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-08-28 11:37 +02:00
Parents9bd245c59c01, 8316df12c77c

Browse the files at this changeset

16 files changed

modified changelog/README.md +4 −0
@@ -39,6 +39,10 @@
3939 - [bug] LoadBalancingPolicy.distance() called before init() (JAVA-784)
4040 - [new feature] Make driver-side metadata optional (JAVA-828)
4141 - [improvement] Allow hosts to remain partially up (JAVA-544)
42+- [improvement] Remove internal blocking calls and expose async session
43+ creation (JAVA-821, JAVA-822)
44+- [improvement] Use parallel calls when re-preparing statement on other
45+ hosts (JAVA-725)
4246
4347 Merged from 2.0.10_fixes branch:
4448
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +4 −4
@@ -26,7 +26,7 @@
2626 *
2727 * This is primarly intended to make mocking easier.
2828 */
29-public abstract class AbstractSession implements Session {
29+public abstract class AbstractSession implements Session, AsyncInitSession {
3030
3131 /**
3232 * {@inheritDoc}
@@ -76,7 +76,7 @@
7676 try {
7777 return Uninterruptibles.getUninterruptibly(prepareAsync(query));
7878 } catch (ExecutionException e) {
79- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
79+ throw DriverThrowables.propagateCause(e);
8080 }
8181 }
8282
@@ -88,7 +88,7 @@
8888 try {
8989 return Uninterruptibles.getUninterruptibly(prepareAsync(statement));
9090 } catch (ExecutionException e) {
91- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
91+ throw DriverThrowables.propagateCause(e);
9292 }
9393 }
9494
@@ -125,7 +125,7 @@
125125 try {
126126 closeAsync().get();
127127 } catch (ExecutionException e) {
128- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
128+ throw DriverThrowables.propagateCause(e);
129129 } catch (InterruptedException e) {
130130 Thread.currentThread().interrupt();
131131 }
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +1 −1
@@ -276,7 +276,7 @@
276276 try {
277277 Uninterruptibles.getUninterruptibly(fetchMoreResults());
278278 } catch (ExecutionException e) {
279- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
279+ throw DriverThrowables.propagateCause(e);
280280 }
281281 }
282282 }
added driver-core/src/main/java/com/datastax/driver/core/AsyncInitSession.java +36 −0
@@ -0,0 +1,36 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.google.common.util.concurrent.ListenableFuture;
19+
20+/**
21+ * A {@link Session} that can be initialized asynchronously.
22+ *
23+ * This interface exists only for backward compatibility reasons: {@link #initAsync()} should really be
24+ * defined by {@link Session}, but adding it after the fact would break binary compatibility.
25+ *
26+ * By default, all sessions returned by the driver implement this interface. The only way you would get
27+ * sessions that don't is if you use a custom {@link Cluster} subclass.
28+ */
29+public interface AsyncInitSession extends Session {
30+ /**
31+ * Initialize this session asynchronously.
32+ *
33+ * @return a future that will complete when the session is fully initialized.
34+ */
35+ ListenableFuture<Session> initAsync();
36+}
added driver-core/src/main/java/com/datastax/driver/core/ChainedResultSetFuture.java +75 −0
@@ -0,0 +1,75 @@
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.concurrent.ExecutionException;
19+import java.util.concurrent.TimeUnit;
20+import java.util.concurrent.TimeoutException;
21+
22+import com.google.common.util.concurrent.AbstractFuture;
23+import com.google.common.util.concurrent.FutureCallback;
24+import com.google.common.util.concurrent.Futures;
25+import com.google.common.util.concurrent.Uninterruptibles;
26+
27+/**
28+ * A {@code ResultSetFuture} that will complete when its source future completes.
29+ */
30+class ChainedResultSetFuture extends AbstractFuture<ResultSet> implements ResultSetFuture {
31+
32+ private volatile ResultSetFuture source;
33+
34+ void setSource(ResultSetFuture source) {
35+ if (this.isCancelled())
36+ source.cancel(false);
37+ this.source = source;
38+ Futures.addCallback(source, new FutureCallback<ResultSet>() {
39+ @Override
40+ public void onSuccess(ResultSet result) {
41+ ChainedResultSetFuture.this.set(result);
42+ }
43+
44+ @Override
45+ public void onFailure(Throwable t) {
46+ ChainedResultSetFuture.this.setException(t);
47+ }
48+ });
49+ }
50+
51+ @Override
52+ public boolean cancel(boolean mayInterruptIfRunning) {
53+ return (source == null || source.cancel(mayInterruptIfRunning))
54+ && super.cancel(mayInterruptIfRunning);
55+ }
56+
57+ @Override
58+ public ResultSet getUninterruptibly() {
59+ try {
60+ return Uninterruptibles.getUninterruptibly(this);
61+ } catch (ExecutionException e) {
62+ throw DriverThrowables.propagateCause(e);
63+ }
64+ }
65+
66+ @Override
67+ public ResultSet getUninterruptibly(long timeout, TimeUnit unit) throws TimeoutException {
68+ try {
69+ return Uninterruptibles.getUninterruptibly(this, timeout, unit);
70+ } catch (ExecutionException e) {
71+ throw DriverThrowables.propagateCause(e);
72+ }
73+ }
74+}
75+
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +76 −29
@@ -28,6 +28,7 @@
2828 import com.google.common.annotations.VisibleForTesting;
2929 import com.google.common.base.Objects;
3030 import com.google.common.base.Predicates;
31+import com.google.common.base.Throwables;
3132 import com.google.common.collect.*;
3233 import com.google.common.util.concurrent.*;
3334 import org.slf4j.Logger;
@@ -220,7 +221,7 @@
220221 */
221222 public Session newSession() {
222223 checkNotClosed(manager);
223- return manager.newSession();
224+ return manager.newSession(null);
224225 }
225226
226227 /**
@@ -244,11 +245,11 @@
244245 * Cluster.
245246 */
246247 public Session connect() {
247- checkNotClosed(manager);
248- init();
249- Session session = manager.newSession();
250- session.init();
251- return session;
248+ try {
249+ return Uninterruptibles.getUninterruptibly(connectAsync());
250+ } catch (ExecutionException e) {
251+ throw DriverThrowables.propagateCause(e);
252+ }
252253 }
253254
254255 /**
@@ -277,25 +278,67 @@
277278 * Cluster.
278279 */
279280 public Session connect(String keyspace) {
280- long timeout = getConfiguration().getSocketOptions().getConnectTimeoutMillis();
281- Session session = connect();
282281 try {
283- try {
284- ResultSetFuture future = session.executeAsync("USE " + keyspace);
285- // Note: using the connection timeout isn't perfectly correct, we should probably change that someday
286- Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS);
287- return session;
288- } catch (TimeoutException e) {
289- throw new DriverInternalError(String.format("No responses after %d milliseconds while setting current keyspace. This should not happen, unless you have setup a very low connection timeout.", timeout));
290- } catch (ExecutionException e) {
291- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
292- }
293- } catch (RuntimeException e) {
294- session.close();
295- throw e;
282+ return Uninterruptibles.getUninterruptibly(connectAsync(keyspace));
283+ } catch (ExecutionException e) {
284+ throw DriverThrowables.propagateCause(e);
296285 }
297286 }
298287
288+ /**
289+ * Creates a new session on this cluster and initializes it asynchronously.
290+ *
291+ * This will also initialize the {@code Cluster} if needed; note that cluster
292+ * initialization happens synchronously on the thread that called this method.
293+ * Therefore it is recommended to initialize the cluster at application
294+ * startup, and not rely on this method to do it.
295+ *
296+ * @return a future that will complete when the session is fully initialized.
297+ *
298+ * @throws NoHostAvailableException if the Cluster has not been initialized
299+ * yet ({@link #init} has not been called and this is the first connect call)
300+ * and no host amongst the contact points can be reached.
301+ *
302+ * @throws IllegalStateException if the Cluster was closed prior to calling
303+ * this method. This can occur either directly (through {@link #close()} or
304+ * {@link #closeAsync()}), or as a result of an error while initializing the
305+ * Cluster.
306+ *
307+ * @see #connect()
308+ */
309+ public ListenableFuture<Session> connectAsync() {
310+ return connectAsync(null);
311+ }
312+
313+ /**
314+ * Creates a new session on this cluster, and initializes it to the given
315+ * keyspace asynchronously.
316+ *
317+ * This will also initialize the {@code Cluster} if needed; note that cluster
318+ * initialization happens synchronously on the thread that called this method.
319+ * Therefore it is recommended to initialize the cluster at application
320+ * startup, and not rely on this method to do it.
321+ *
322+ * @param keyspace The name of the keyspace to use for the created
323+ * {@code Session}.
324+ * @return a future that will complete when the session is fully initialized.
325+ *
326+ * @throws NoHostAvailableException if the Cluster has not been initialized
327+ * yet ({@link #init} has not been called and this is the first connect call)
328+ * and no host amongst the contact points can be reached.
329+ *
330+ * @throws IllegalStateException if the Cluster was closed prior to calling
331+ * this method. This can occur either directly (through {@link #close()} or
332+ * {@link #closeAsync()}), or as a result of an error while initializing the
333+ * Cluster.
334+ */
335+ public ListenableFuture<Session> connectAsync(String keyspace) {
336+ checkNotClosed(manager);
337+ init();
338+ AsyncInitSession session = manager.newSession(keyspace);
339+ return session.initAsync();
340+ }
341+
299342 /**
300343 * The name of this cluster object.
301344 * <p>
@@ -500,7 +543,7 @@
500543 try {
501544 closeAsync().get();
502545 } catch (ExecutionException e) {
503- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
546+ throw DriverThrowables.propagateCause(e);
504547 } catch (InterruptedException e) {
505548 Thread.currentThread().interrupt();
506549 }
@@ -1444,8 +1487,8 @@
14441487 return translated == null ? sa : translated;
14451488 }
14461489
1447- private Session newSession() {
1448- SessionManager session = new SessionManager(Cluster.this);
1490+ private AsyncInitSession newSession(String keyspace) {
1491+ SessionManager session = new SessionManager(Cluster.this, keyspace);
14491492 sessions.add(session);
14501493 return session;
14511494 }
@@ -1643,7 +1686,7 @@
16431686 // Now, check if there isn't pools to create/remove following the addition.
16441687 // We do that now only so that it's not called before we've set the node up.
16451688 for (SessionManager s : sessions)
1646- s.updateCreatedPools();
1689+ s.updateCreatedPools().get();
16471690
16481691 } finally {
16491692 host.notificationsLock.unlock();
@@ -1882,7 +1925,7 @@
18821925
18831926 List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
18841927 for (SessionManager s : sessions)
1885- futures.add(s.maybeAddPool(host, reusedConnection));
1928+ futures.add(s.maybeAddPool(host, reusedConnection, false));
18861929
18871930 try {
18881931 // Only mark the node up once all session have added their pool (if the load-balancing
@@ -1912,7 +1955,7 @@
19121955 // Now, check if there isn't pools to create/remove following the addition.
19131956 // We do that now only so that it's not called before we've set the node up.
19141957 for (SessionManager s : sessions)
1915- s.updateCreatedPools();
1958+ s.updateCreatedPools().get();
19161959
19171960 } finally {
19181961 host.notificationsLock.unlock();
@@ -2260,8 +2303,12 @@
22602303 if (ccHost == null || loadBalancingPolicy().distance(ccHost) != HostDistance.LOCAL)
22612304 controlConnection.triggerReconnect();
22622305
2263- for (SessionManager s : sessions)
2264- s.updateCreatedPools();
2306+ try {
2307+ for (SessionManager s : sessions)
2308+ Uninterruptibles.getUninterruptibly(s.updateCreatedPools());
2309+ } catch (ExecutionException e) {
2310+ throw DriverThrowables.propagateCause(e);
2311+ }
22652312 }
22662313
22672314 void refreshConnectedHost(Host host) {
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +40 −25
@@ -35,7 +35,6 @@
3535 import io.netty.handler.ssl.SslHandler;
3636 import io.netty.handler.timeout.IdleStateEvent;
3737 import io.netty.handler.timeout.IdleStateHandler;
38-import io.netty.util.HashedWheelTimer;
3938 import io.netty.util.Timeout;
4039 import io.netty.util.Timer;
4140 import io.netty.util.TimerTask;
@@ -48,8 +47,13 @@
4847
4948 import com.datastax.driver.core.exceptions.AuthenticationException;
5049 import com.datastax.driver.core.exceptions.DriverException;
50+import com.datastax.driver.core.exceptions.DriverInternalError;
51+import com.datastax.driver.core.exceptions.InvalidQueryException;
5152 import com.datastax.driver.core.utils.MoreFutures;
5253
54+import static com.datastax.driver.core.Message.Response.Type.ERROR;
55+import static com.datastax.driver.core.Message.Response.Type.RESULT;
56+
5357 // For LoggingHandler
5458 //import org.jboss.netty.handler.logging.LoggingHandler;
5559 //import org.jboss.netty.logging.InternalLogLevel;
@@ -175,8 +179,8 @@
175179 public ListenableFuture<Void> create(Throwable t) throws Exception {
176180 SettableFuture<Void> future = SettableFuture.create();
177181 // Make sure the connection gets properly closed.
178- if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException) {
179- // These exceptions cause the node to be ignored, so just propagate
182+ if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException || t instanceof SetKeyspaceException) {
183+ // Just propagate
180184 closeAsync().force();
181185 future.setException(t);
182186 } else {
@@ -197,7 +201,7 @@
197201 @Override
198202 public void onSuccess(Void result) {
199203 Host host = factory.manager.metadata.getHost(address);
200- if(host != null)
204+ if (host != null)
201205 host.convictionPolicy.signalConnectionCreated();
202206 isInitialized = true;
203207 }
@@ -435,28 +439,11 @@
435439 if (this.keyspace != null && this.keyspace.equals(keyspace))
436440 return;
437441
438- Future future = null;
442+ ListenableFuture<Void> future = null;
439443 try {
440- logger.trace("{} Setting keyspace {}", this, keyspace);
441444 long timeout = factory.getConnectTimeoutMillis();
442- // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already
443- future = write(new Requests.Query("USE \"" + keyspace + '"'));
444- Message.Response response = Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS);
445- switch (response.type) {
446- case RESULT:
447- this.keyspace = keyspace;
448- break;
449- default:
450- // The code set the keyspace only when a successful 'use'
451- // has been perform, so there shouldn't be any error here.
452- // It can happen however that the node we're connecting to
453- // is not up on the schema yet. In that case, defuncting
454- // the connection is not a bad choice.
455- String message = String.format("Problem while setting keyspace, got %s as response", response);
456- logger.warn("{} {}", this, message);
457- defunct(new ConnectionException(address, message));
458- break;
459- }
445+ future = setKeyspaceAsync(keyspace);
446+ Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS);
460447 } catch (ConnectionException e) {
461448 throw defunct(e);
462449 } catch (TimeoutException e) {
@@ -471,10 +458,38 @@
471458 logger.warn(String.format("Tried to set the keyspace on busy connection to %s. This should not happen but is not critical (it will retried)", address));
472459 throw new ConnectionException(address, "Tried to set the keyspace on busy connection");
473460 } catch (ExecutionException e) {
474- throw defunct(new ConnectionException(address, "Error while setting keyspace", e));
461+ throw defunct(new ConnectionException(address, "Error while setting keyspace", e.getCause()));
475462 }
476463 }
477464
465+ ListenableFuture<Void> setKeyspaceAsync(final String keyspace) throws ConnectionException, BusyConnectionException {
466+ logger.trace("{} Setting keyspace {}", this, keyspace);
467+ // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already
468+ Future future = write(new Requests.Query("USE \"" + keyspace + '"'));
469+ return Futures.transform(future, new AsyncFunction<Message.Response, Void>() {
470+ @Override
471+ public ListenableFuture<Void> apply(Message.Response response) throws Exception {
472+ if (response.type == RESULT) {
473+ Connection.this.keyspace = keyspace;
474+ return MoreFutures.VOID_SUCCESS;
475+ } else if (response.type == ERROR) {
476+ closeAsync().force();
477+ Responses.Error error = (Responses.Error)response;
478+ Exception e = error.asException(address);
479+ if (e instanceof InvalidQueryException) {
480+ // Most likely means that the keyspace name is wrong. Wrap that in a specific exception, because we want
481+ // to treat it specially in case of a Session init.
482+ e = new SetKeyspaceException(e);
483+ }
484+ throw e;
485+ } else {
486+ closeAsync().force();
487+ throw new DriverInternalError("Unexpected response while setting keyspace: " + response);
488+ }
489+ }
490+ }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor());
491+ }
492+
478493 /**
479494 * Write a request on this connection.
480495 *
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +2 −14
@@ -198,7 +198,7 @@
198198 try {
199199 return Uninterruptibles.getUninterruptibly(this);
200200 } catch (ExecutionException e) {
201- throw extractCauseFromExecutionException(e);
201+ throw DriverThrowables.propagateCause(e);
202202 }
203203 }
204204
@@ -230,7 +230,7 @@
230230 try {
231231 return Uninterruptibles.getUninterruptibly(this, timeout, unit);
232232 } catch (ExecutionException e) {
233- throw extractCauseFromExecutionException(e);
233+ throw DriverThrowables.propagateCause(e);
234234 }
235235 }
236236
@@ -277,18 +277,6 @@
277277 return true;
278278 }
279279
280- static RuntimeException extractCauseFromExecutionException(ExecutionException e) {
281- // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been
282- // created on the I/O thread receiving the response. Which means that the stacktrace associated
283- // with said cause will make no mention of the current thread. This is painful for say, finding
284- // out which execute() statement actually raised the exception. So instead, we re-create the
285- // exception.
286- if (e.getCause() instanceof DriverException)
287- throw ((DriverException)e.getCause()).copy();
288- else
289- throw new DriverInternalError("Unexpected exception thrown", e.getCause());
290- }
291-
292280 @Override
293281 public int retryCount() {
294282 // This is only called for internal calls (i.e, when the future is not wrapped in RequestHandler).
modified driver-core/src/main/java/com/datastax/driver/core/DelegatingCluster.java +12 −0
@@ -18,6 +18,8 @@
1818 import java.net.InetSocketAddress;
1919 import java.util.Collections;
2020
21+import com.google.common.util.concurrent.ListenableFuture;
22+
2123 /**
2224 * Base class for custom {@link Cluster} implementations that wrap another instance (delegate / decorator pattern).
2325 */
@@ -74,6 +76,16 @@
7476 return delegate().connect(keyspace);
7577 }
7678
79+ @Override
80+ public ListenableFuture<Session> connectAsync() {
81+ return delegate().connectAsync();
82+ }
83+
84+ @Override
85+ public ListenableFuture<Session> connectAsync(String keyspace) {
86+ return delegate().connectAsync(keyspace);
87+ }
88+
7789 @Override
7890 public Metadata getMetadata() {
7991 return delegate().getMetadata();
added driver-core/src/main/java/com/datastax/driver/core/DriverThrowables.java +41 −0
@@ -0,0 +1,41 @@
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.concurrent.ExecutionException;
19+
20+import com.datastax.driver.core.exceptions.DriverException;
21+import com.datastax.driver.core.exceptions.DriverInternalError;
22+
23+class DriverThrowables {
24+
25+ static RuntimeException propagateCause(ExecutionException e) {
26+ Throwable cause = e.getCause();
27+
28+ if (cause instanceof Error)
29+ throw ((Error)cause);
30+
31+ // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been
32+ // created on the I/O thread receiving the response. Which means that the stacktrace associated
33+ // with said cause will make no mention of the current thread. This is painful for say, finding
34+ // out which execute() statement actually raised the exception. So instead, we re-create the
35+ // exception.
36+ if (cause instanceof DriverException)
37+ throw ((DriverException)cause).copy();
38+ else
39+ throw new DriverInternalError("Unexpected exception thrown", cause);
40+ }
41+}
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +53 −11
@@ -26,11 +26,9 @@
2626 import java.util.concurrent.locks.Lock;
2727 import java.util.concurrent.locks.ReentrantLock;
2828
29+import com.google.common.base.Throwables;
2930 import com.google.common.collect.Lists;
30-import com.google.common.util.concurrent.Futures;
31-import com.google.common.util.concurrent.ListenableFuture;
32-import com.google.common.util.concurrent.MoreExecutors;
33-import com.google.common.util.concurrent.SettableFuture;
31+import com.google.common.util.concurrent.*;
3432 import org.slf4j.Logger;
3533 import org.slf4j.LoggerFactory;
3634
@@ -102,6 +100,10 @@
102100 * pool.
103101 */
104102 public ListenableFuture<Void> initAsync(Connection reusedConnection) {
103+ String keyspace = manager.poolsState.keyspace;
104+
105+ Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
106+
105107 // Create initial core connections
106108 final int coreSize = options().getCoreConnectionsPerHost(hostDistance);
107109 final List<Connection> connections = Lists.newArrayListWithCapacity(coreSize);
@@ -119,15 +121,13 @@
119121 }
120122 reusedConnection = null;
121123 connections.add(connection);
122- connectionFutures.add(connectionFuture);
124+ connectionFutures.add(handleErrors(setKeyspaceAsync(connectionFuture, connection, keyspace), initExecutor));
123125 }
124126
125- Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
126-
127- ListenableFuture<List<Void>> allConnectionsFuture = Futures.successfulAsList(connectionFutures);
127+ ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures);
128128
129129 final SettableFuture<Void> initFuture = SettableFuture.create();
130- Futures.addCallback(allConnectionsFuture, new MoreFutures.SuccessCallback<List<Void>>() {
130+ Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() {
131131 @Override
132132 public void onSuccess(List<Void> l) {
133133 // Some of the connections might have failed, keep only the successful ones
@@ -151,11 +151,48 @@
151151 initFuture.set(null);
152152 }
153153 }
154+
155+ @Override
156+ public void onFailure(Throwable t) {
157+ phase.compareAndSet(Phase.INITIALIZING, Phase.INIT_FAILED);
158+ forceClose(connections);
159+ initFuture.setException(t);
160+ }
154161 }, initExecutor);
155162 return initFuture;
156163 }
157164
158- // Clean up if we got an error at construction time but still created part of the core connections
165+ private ListenableFuture<Void> handleErrors(ListenableFuture<Void> connectionInitFuture, Executor executor) {
166+ return Futures.withFallback(connectionInitFuture, new FutureFallback<Void>() {
167+ @Override
168+ public ListenableFuture<Void> create(Throwable t) throws Exception {
169+ // Propagate these exceptions because they mean no connection will ever succeed. They will be handled
170+ // accordingly in SessionManager#maybeAddPool.
171+ Throwables.propagateIfInstanceOf(t, ClusterNameMismatchException.class);
172+ Throwables.propagateIfInstanceOf(t, UnsupportedProtocolVersionException.class);
173+ Throwables.propagateIfInstanceOf(t, SetKeyspaceException.class);
174+
175+ // We don't want to swallow Errors either as they probably indicate a more serious issue (OOME...)
176+ Throwables.propagateIfInstanceOf(t, Error.class);
177+
178+ // Otherwise, return success. The pool will simply ignore this connection when it sees that it's been closed.
179+ return MoreFutures.VOID_SUCCESS;
180+ }
181+ }, executor);
182+ }
183+
184+ private ListenableFuture<Void> setKeyspaceAsync(ListenableFuture<Void> initFuture, final Connection connection, final String keyspace) {
185+ return (keyspace == null)
186+ ? initFuture
187+ : Futures.transform(initFuture, new AsyncFunction<Void, Void>() {
188+ @Override
189+ public ListenableFuture<Void> apply(Void input) throws Exception {
190+ return connection.setKeyspaceAsync(keyspace);
191+ }
192+ });
193+ }
194+
195+ // Clean up if we got a fatal error at construction time but still created part of the core connections
159196 private void forceClose(List<Connection> connections) {
160197 for (Connection connection : connections) {
161198 connection.closeAsync().force();
@@ -423,6 +460,7 @@
423460 }
424461 logger.debug("Creating new connection on busy pool to {}", host);
425462 newConnection = manager.connectionFactory().open(this);
463+ newConnection.setKeyspace(manager.poolsState.keyspace);
426464 }
427465 connections.add(newConnection);
428466
@@ -644,7 +682,11 @@
644682
645683 volatile String keyspace;
646684
647- public void setKeyspace(String keyspace) {
685+ PoolState(String keyspace) {
686+ this.keyspace = keyspace;
687+ }
688+
689+ void setKeyspace(String keyspace) {
648690 this.keyspace = keyspace;
649691 }
650692 }
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +4 −0
@@ -385,6 +385,10 @@
385385 * Requests the driver to re-evaluate the {@link HostDistance} (through the configured
386386 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known
387387 * hosts and to drop/add connections to each hosts according to the computed distance.
388+ * <p>
389+ * Note that, due to backward compatibility issues, this method is not interruptible. If the
390+ * caller thread gets interrupted, the method will complete and only then re-interrupt the
391+ * thread (which you can check with {@code Thread.currentThread().isInterrupted()}).
388392 */
389393 public void refreshConnectedHosts() {
390394 manager.refreshConnectedHosts();
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +163 −112
@@ -22,12 +22,15 @@
2222 import java.util.concurrent.atomic.AtomicReference;
2323
2424 import com.google.common.base.Function;
25+import com.google.common.base.Functions;
26+import com.google.common.base.Throwables;
2527 import com.google.common.collect.ImmutableList;
2628 import com.google.common.collect.Lists;
2729 import com.google.common.util.concurrent.*;
2830 import org.slf4j.Logger;
2931 import org.slf4j.LoggerFactory;
3032
33+import com.datastax.driver.core.Message.Response;
3134 import com.datastax.driver.core.exceptions.DriverInternalError;
3235 import com.datastax.driver.core.exceptions.InvalidQueryException;
3336 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
@@ -46,55 +49,98 @@
4649 final Cluster cluster;
4750 final ConcurrentMap<Host, HostConnectionPool> pools;
4851 final HostConnectionPool.PoolState poolsState;
52+ private final AtomicReference<ListenableFuture<Session>> initFuture = new AtomicReference<ListenableFuture<Session>>();
4953 final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
5054
5155 private volatile boolean isInit;
5256 private volatile boolean isClosing;
5357
5458 // Package protected, only Cluster should construct that.
55- SessionManager(Cluster cluster) {
59+ SessionManager(Cluster cluster, String keyspace) {
5660 this.cluster = cluster;
5761 this.pools = new ConcurrentHashMap<Host, HostConnectionPool>();
58- this.poolsState = new HostConnectionPool.PoolState();
62+ this.poolsState = new HostConnectionPool.PoolState(keyspace);
5963 }
6064
61- public synchronized Session init() {
62- if (isInit)
63- return this;
65+ public Session init() {
66+ try {
67+ return Uninterruptibles.getUninterruptibly(initAsync());
68+ } catch (ExecutionException e) {
69+ throw DriverThrowables.propagateCause(e);
70+ }
71+ }
6472
73+ public ListenableFuture<Session> initAsync() {
6574 // If we haven't initialized the cluster, do it now
6675 cluster.init();
6776
68- // Create pools to initial nodes (and wait for them to be created)
77+ ListenableFuture<Session> existing = initFuture.get();
78+ if (existing != null)
79+ return existing;
80+
81+ final SettableFuture<Session> myInitFuture = SettableFuture.create();
82+ if (!initFuture.compareAndSet(null, myInitFuture))
83+ return initFuture.get();
84+
6985 Collection<Host> hosts = cluster.getMetadata().allHosts();
70- createPoolsInParallel(hosts);
71-
72- isInit = true;
73- updateCreatedPools();
74- return this;
86+ ListenableFuture<?> allPoolsCreatedFuture = createPools(hosts);
87+ ListenableFuture<?> allPoolsUpdatedFuture = Futures.transform(allPoolsCreatedFuture,
88+ new AsyncFunction<Object, Object>() {
89+ @Override
90+ @SuppressWarnings("unchecked")
91+ public ListenableFuture<Object> apply(Object input) throws Exception {
92+ isInit = true;
93+ return (ListenableFuture<Object>)updateCreatedPools();
94+ }
95+ });
96+
97+ Futures.addCallback(allPoolsUpdatedFuture, new FutureCallback<Object>() {
98+ @Override
99+ public void onSuccess(Object result) {
100+ myInitFuture.set(SessionManager.this);
101+ }
102+
103+ @Override
104+ public void onFailure(Throwable t) {
105+ SessionManager.this.closeAsync(); // don't leak the session
106+ myInitFuture.setException(t);
107+ }
108+ });
109+ return myInitFuture;
75110 }
76111
77- private void createPoolsInParallel(Collection<Host> hosts) {
112+ private ListenableFuture<?> createPools(Collection<Host> hosts) {
78113 List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size());
79114 for (Host host : hosts)
80115 if (host.state != Host.State.DOWN)
81- futures.add(maybeAddPool(host, null));
82- try {
83- Futures.successfulAsList(futures).get();
84- } catch (ExecutionException e) {
85- // Won't happen because we used successfulAsList
86- // And if a particular pool failed, maybeAddPool already handled it
87- } catch (InterruptedException e) {
88- Thread.currentThread().interrupt();
89- }
116+ futures.add(maybeAddPool(host, null, true));
117+ return Futures.allAsList(futures);
90118 }
91119
92120 public String getLoggedKeyspace() {
93121 return poolsState.keyspace;
94122 }
95123
96- public ResultSetFuture executeAsync(Statement statement) {
97- return executeQuery(makeRequestMessage(statement, null), statement);
124+ public ResultSetFuture executeAsync(final Statement statement) {
125+ if (isInit) {
126+ DefaultResultSetFuture future = new DefaultResultSetFuture(this, makeRequestMessage(statement, null));
127+ new RequestHandler(this, future, statement).sendRequest();
128+ return future;
129+ } else {
130+ // If the session is not initialized, we can't call makeRequestMessage() synchronously, because it
131+ // requires internal Cluster state that might not be initialized yet (like the protocol version).
132+ // Because of the way the future is built, we need another 'proxy' future that we can return now.
133+ final ChainedResultSetFuture chainedFuture = new ChainedResultSetFuture();
134+ this.initAsync().addListener(new Runnable() {
135+ @Override
136+ public void run() {
137+ DefaultResultSetFuture actualFuture = new DefaultResultSetFuture(SessionManager.this, makeRequestMessage(statement, null));
138+ execute(actualFuture, statement);
139+ chainedFuture.setSource(actualFuture);
140+ }
141+ }, executor());
142+ return chainedFuture;
143+ }
98144 }
99145
100146 public ListenableFuture<PreparedStatement> prepareAsync(String query) {
@@ -135,8 +181,8 @@
135181 }
136182
137183 private ListenableFuture<PreparedStatement> toPreparedStatement(final String query, final Connection.Future future) {
138- return Futures.transform(future, new Function<Message.Response, PreparedStatement>() {
139- public PreparedStatement apply(Message.Response response) {
184+ return Futures.transform(future, new AsyncFunction<Response, PreparedStatement>() {
185+ public ListenableFuture<PreparedStatement> apply(Response response) {
140186 switch (response.type) {
141187 case RESULT:
142188 Responses.Result rm = (Responses.Result)response;
@@ -145,29 +191,26 @@
145191 Responses.Result.Prepared pmsg = (Responses.Result.Prepared)rm;
146192 PreparedStatement stmt = DefaultPreparedStatement.fromMessage(pmsg, cluster.getMetadata(), query, poolsState.keyspace);
147193 stmt = cluster.manager.addPrepared(stmt);
148- if (cluster.getConfiguration().getQueryOptions().isPrepareOnAllHosts()){
149- try {
150- // All Sessions are connected to the same nodes so it's enough to prepare only the nodes of this session.
151- // If that changes, we'll have to make sure this propagate to other sessions too.
152- prepare(stmt.getQueryString(), future.getAddress());
153- } catch (InterruptedException e) {
154- Thread.currentThread().interrupt();
155- // This method doesn't propagate interruption, at least not for now. However, if we've
156- // interrupted preparing queries on other node it's not a problem as we'll re-prepare
157- // later if need be. So just ignore.
158- }
194+ if (cluster.getConfiguration().getQueryOptions().isPrepareOnAllHosts()) {
195+ // All Sessions are connected to the same nodes so it's enough to prepare only the nodes of this session.
196+ // If that changes, we'll have to make sure this propagate to other sessions too.
197+ return prepare(stmt, future.getAddress());
198+ } else {
199+ return Futures.immediateFuture(stmt);
159200 }
160- return stmt;
161201 default:
162- throw new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind));
202+ return Futures.immediateFailedFuture(
203+ new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind)));
163204 }
164205 case ERROR:
165- throw ((Responses.Error)response).asException(future.getAddress());
206+ return Futures.immediateFailedFuture(
207+ ((Responses.Error)response).asException(future.getAddress()));
166208 default:
167- throw new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type));
209+ return Futures.immediateFailedFuture(
210+ new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type)));
168211 }
169212 }
170- }, executor()); // Since the transformation involves querying other nodes, we should not do that in an I/O thread
213+ });
171214 }
172215
173216 Connection.Factory connectionFactory() {
@@ -285,7 +328,7 @@
285328 }
286329
287330 // Returns whether there was problem creating the pool
288- ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection) {
331+ ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection, final boolean failOnKeyspaceError) {
289332 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
290333 if (distance == HostDistance.IGNORED)
291334 return Futures.immediateFuture(true);
@@ -318,6 +361,9 @@
318361 ClusterNameMismatchException e = (ClusterNameMismatchException)t;
319362 cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
320363 cluster.manager.triggerOnDown(host, false);
364+ } else if ((t instanceof SetKeyspaceException) && failOnKeyspaceError) {
365+ future.setException(t.getCause());
366+ return;
321367 } else {
322368 logger.error("Error creating pool to " + host, t);
323369 }
@@ -345,54 +391,48 @@
345391 * This method ensures that all hosts for which a pool should exist
346392 * have one, and hosts that shouldn't don't.
347393 */
348- void updateCreatedPools() {
394+ ListenableFuture<?> updateCreatedPools() {
349395 // This method does nothing during initialization. Some hosts may be non-responsive but not yet marked DOWN; if
350396 // we execute the code below we would try to create their pool over and over again.
351397 // It's called explicitly at the end of init(), once isInit has been set to true.
352398 if (!isInit)
353- return;
399+ return MoreFutures.VOID_SUCCESS;
354400
355- try {
356- // We do 2 iterations, so that we add missing pools first, and them remove all unecessary pool second.
357- // That way, we'll avoid situation where we'll temporarily lose connectivity
358- List<Host> toRemove = new ArrayList<Host>();
359- List<ListenableFuture<?>> poolCreationFutures = new ArrayList<ListenableFuture<?>>();
360-
361- for (Host h : cluster.getMetadata().allHosts()) {
362- HostDistance dist = loadBalancingPolicy().distance(h);
363- HostConnectionPool pool = pools.get(h);
364-
365- if (pool == null) {
366- if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
367- poolCreationFutures.add(maybeAddPool(h, null));
368- } else if (dist != pool.hostDistance) {
369- if (dist == HostDistance.IGNORED) {
370- toRemove.add(h);
371- } else {
372- pool.hostDistance = dist;
373- pool.ensureCoreConnections();
374- }
375- }
376- }
401+ // We do 2 iterations, so that we add missing pools first, and them remove all unecessary pool second.
402+ // That way, we'll avoid situation where we'll temporarily lose connectivity
403+ final List<Host> toRemove = new ArrayList<Host>();
404+ List<ListenableFuture<Boolean>> poolCreatedFutures = Lists.newArrayList();
377405
378- // Wait pool creation before removing, so we don't lose connectivity
379- try {
380- Futures.successfulAsList(poolCreationFutures).get();
381- } catch (ExecutionException e) {
382- // Won't happen because we used successfulAsList
383- // And if a particular pool failed, maybeAddPool already handled it
406+ for (Host h : cluster.getMetadata().allHosts()) {
407+ HostDistance dist = loadBalancingPolicy().distance(h);
408+ HostConnectionPool pool = pools.get(h);
409+
410+ if (pool == null) {
411+ if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
412+ poolCreatedFutures.add(maybeAddPool(h, null, false));
413+ } else if (dist != pool.hostDistance) {
414+ if (dist == HostDistance.IGNORED) {
415+ toRemove.add(h);
416+ } else {
417+ pool.hostDistance = dist;
418+ pool.ensureCoreConnections();
419+ }
384420 }
421+ }
385422
386- List<ListenableFuture<?>> poolRemovalFutures = new ArrayList<ListenableFuture<?>>(toRemove.size());
387- for (Host h : toRemove)
388- poolRemovalFutures.add(removePool(h));
423+ // Wait pool creation before removing, so we don't lose connectivity
424+ ListenableFuture<?> allPoolsCreatedFuture = Futures.successfulAsList(poolCreatedFutures);
389425
390- Futures.allAsList(poolRemovalFutures).get();
391- } catch (InterruptedException e) {
392- Thread.currentThread().interrupt();
393- } catch (ExecutionException e) {
394- logger.error("Unexpected error while refreshing connection pools", e.getCause());
395- }
426+ return Futures.transform(allPoolsCreatedFuture, new AsyncFunction<Object, List<Void>>() {
427+ @Override
428+ public ListenableFuture<List<Void>> apply(Object input) throws Exception {
429+ List<ListenableFuture<Void>> poolRemovedFuture = Lists.newArrayListWithCapacity(toRemove.size());
430+ for (Host h : toRemove)
431+ poolRemovedFuture.add(removePool(h));
432+
433+ return Futures.successfulAsList(poolRemovedFuture);
434+ }
435+ });
396436 }
397437
398438 void updateCreatedPools(Host h) {
@@ -403,7 +443,7 @@
403443 if (pool == null) {
404444 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
405445 try {
406- maybeAddPool(h, null).get();
446+ maybeAddPool(h, null, false).get();
407447 } catch (ExecutionException e) {
408448 // Ignore, maybeAddPool has already handled the error
409449 }
@@ -426,7 +466,7 @@
426466 // Note that with well behaved balancing policy (that ignore dead nodes), the removePool call is not necessary
427467 // since updateCreatedPools should take care of it. But better protect against non well behaving policies.
428468 removePool(host).force().get();
429- updateCreatedPools();
469+ updateCreatedPools().get();
430470 }
431471
432472 void onRemove(Host host) throws InterruptedException, ExecutionException {
@@ -442,7 +482,7 @@
442482 } catch (TimeoutException e) {
443483 throw new DriverInternalError(String.format("No responses after %d milliseconds while setting current keyspace. This should not happen, unless you have setup a very low connection timeout.", timeout));
444484 } catch (ExecutionException e) {
445- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
485+ throw DriverThrowables.propagateCause(e);
446486 }
447487 }
448488
@@ -528,46 +568,57 @@
528568 * This method will find a suitable node to connect to using the
529569 * {@link LoadBalancingPolicy} and handle host failover.
530570 */
531- void execute(RequestHandler.Callback callback, Statement statement) {
532- // init() locks, so avoid if we know we don't need it.
533- if (!isInit)
534- init();
535- new RequestHandler(this, callback, statement).sendRequest();
571+ void execute(final RequestHandler.Callback callback, final Statement statement) {
572+ if (isInit)
573+ new RequestHandler(this, callback, statement).sendRequest();
574+ else
575+ this.initAsync().addListener(new Runnable() {
576+ @Override
577+ public void run() {
578+ new RequestHandler(SessionManager.this, callback, statement).sendRequest();
579+ }
580+ }, executor());
536581 }
537582
538- private void prepare(String query, InetSocketAddress toExclude) throws InterruptedException {
539- for (Map.Entry<Host, HostConnectionPool> entry : pools.entrySet()) {
583+ private ListenableFuture<PreparedStatement> prepare(final PreparedStatement statement, InetSocketAddress toExclude) {
584+ final String query = statement.getQueryString();
585+ List<ListenableFuture<Response>> futures = Lists.newArrayListWithExpectedSize(pools.size());
586+ for (final Map.Entry<Host, HostConnectionPool> entry : pools.entrySet()) {
540587 if (entry.getKey().getSocketAddress().equals(toExclude))
541588 continue;
542589
543- // Let's not wait too long if we can't get a connection. Things
544- // will fix themselves once the user tries a query anyway.
545- Connection c = null;
546- boolean timedOut = false;
547590 try {
548- c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS);
549- c.write(new Requests.Prepare(query)).get();
550- } catch (ConnectionException e) {
591+ // Preparing is not critical: if it fails, it will fix itself later when the user tries to execute
592+ // the prepared query. So don't block if no connection is available, simply abort.
593+ final Connection c = entry.getValue().borrowConnection(0, TimeUnit.MILLISECONDS);
594+ ListenableFuture<Response> future = c.write(new Requests.Prepare(query));
595+ Futures.addCallback(future, new FutureCallback<Response>() {
596+ @Override
597+ public void onSuccess(Response result) {
598+ c.release();
599+ }
600+
601+ @Override
602+ public void onFailure(Throwable t) {
603+ logger.debug(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), t);
604+
605+ // If the query timed out, that already released the connection, otherwise do it now
606+ if (!(t instanceof OperationTimedOutException))
607+ c.release();
608+ }
609+ });
610+ futures.add(future);
611+ } catch (Exception e) {
551612 // Again, not being able to prepare the query right now is no big deal, so just ignore
552- } catch (BusyConnectionException e) {
553- // Same as above
554- } catch (TimeoutException e) {
555- // Same as above
556- } catch (ExecutionException e) {
557- // We shouldn't really get exception while preparing a
558- // query, so log this (but ignore otherwise as it's not a big deal)
559- logger.error(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), e);
560- // If the query timed out, that already released the connection
561- timedOut = e.getCause() instanceof OperationTimedOutException;
562- } finally {
563- if (c != null && !timedOut)
564- c.release();
565613 }
566614 }
615+ // Return the statement when all futures are done
616+ return Futures.transform(
617+ Futures.successfulAsList(futures),
618+ Functions.constant(statement));
567619 }
568620
569621 ResultSetFuture executeQuery(Message.Request msg, Statement statement) {
570-
571622 DefaultResultSetFuture future = new DefaultResultSetFuture(this, msg);
572623 execute(future, statement);
573624 return future;
added driver-core/src/main/java/com/datastax/driver/core/SetKeyspaceException.java +23 −0
@@ -0,0 +1,23 @@
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+@SuppressWarnings("serial")
19+class SetKeyspaceException extends Exception {
20+ SetKeyspaceException(Exception cause) {
21+ super(cause);
22+ }
23+}
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +78 −3
@@ -16,26 +16,38 @@
1616 package com.datastax.driver.core;
1717
1818 import java.util.Collection;
19+import java.util.concurrent.ExecutionException;
1920 import java.util.concurrent.TimeUnit;
2021
22+import com.google.common.base.Function;
2123 import com.google.common.collect.Lists;
24+import com.google.common.util.concurrent.AsyncFunction;
25+import com.google.common.util.concurrent.Futures;
26+import com.google.common.util.concurrent.ListenableFuture;
27+import com.google.common.util.concurrent.Uninterruptibles;
2228 import org.testng.annotations.Test;
2329
30+import static org.assertj.core.api.Assertions.assertThat;
2431 import static org.testng.Assert.assertEquals;
2532 import static org.testng.Assert.assertTrue;
2633
34+import com.datastax.driver.core.exceptions.InvalidQueryException;
35+
2736 public class AsyncQueryTest extends CCMBridge.PerClassSingleNodeCluster {
2837
2938 @Override
3039 protected Collection<String> getTableDefinitions() {
31- return Lists.newArrayList();
40+ return Lists.newArrayList(
41+ "create table foo(k int primary key, v int)",
42+ "insert into foo (k, v) values (1, 1)"
43+ );
3244 }
3345
3446 /**
3547 * Checks that a cancelled query releases the connection (JAVA-407).
3648 */
3749 @Test(groups = "short")
38- public void cancelQueryTest() throws InterruptedException {
50+ public void cancelled_query_should_release_the_connection() throws InterruptedException {
3951 ResultSetFuture future = session.executeAsync("select release_version from system.local");
4052 future.cancel(true);
4153 assertTrue(future.isCancelled());
@@ -48,8 +60,71 @@
4860 }
4961 }
5062
63+ @Test(groups = "short")
64+ public void should_init_cluster_and_session_if_needed() throws Exception {
65+ // For this test we need an uninitialized cluster, so we can't reuse the one provided by the
66+ // parent class. Rebuild a new one with the same (unique) host.
67+ Host host = cluster.getMetadata().allHosts().iterator().next();
68+
69+ Cluster cluster2 = null;
70+ try {
71+ cluster2 = Cluster.builder()
72+ .addContactPointsWithPorts(Lists.newArrayList(host.getSocketAddress()))
73+ .build();
74+ Session session2 = cluster2.newSession();
75+
76+ // Neither cluster2 nor session2 are initialized at this point
77+ assertThat(cluster2.manager.metadata).isNull();
78+
79+ ResultSetFuture future = session2.executeAsync(String.format("select v from %s.foo where k = 1", keyspace));
80+ Row row = Uninterruptibles.getUninterruptibly(future).one();
81+
82+ assertThat(row.getInt(0)).isEqualTo(1);
83+ } finally {
84+ if (cluster2 != null)
85+ cluster2.close();
86+ }
87+ }
88+
89+ @Test(groups = "short")
90+ public void should_chain_query_on_async_session_init() throws Exception {
91+ ListenableFuture<Integer> resultFuture = connectAndQuery(this.keyspace);
92+
93+ Integer result = Uninterruptibles.getUninterruptibly(resultFuture);
94+ assertThat(result).isEqualTo(1);
95+ }
96+
97+ @Test(groups = "short")
98+ public void should_propagate_error_to_chained_query_if_session_init_fails() throws Exception {
99+ ListenableFuture<Integer> resultFuture = connectAndQuery("wrong_keyspace");
100+
101+ try {
102+ Uninterruptibles.getUninterruptibly(resultFuture);
103+ } catch (ExecutionException e) {
104+ assertThat(e.getCause())
105+ .isInstanceOf(InvalidQueryException.class)
106+ .hasMessage("Keyspace 'wrong_keyspace' does not exist");
107+ }
108+ }
109+
110+ private ListenableFuture<Integer> connectAndQuery(String keyspace) {
111+ ListenableFuture<Session> sessionFuture = cluster.connectAsync(keyspace);
112+ ListenableFuture<ResultSet> queryFuture = Futures.transform(sessionFuture, new AsyncFunction<Session, ResultSet>() {
113+ @Override
114+ public ListenableFuture<ResultSet> apply(Session session) throws Exception {
115+ return session.executeAsync("select v from foo where k = 1");
116+ }
117+ });
118+ return Futures.transform(queryFuture, new Function<ResultSet, Integer>() {
119+ @Override
120+ public Integer apply(ResultSet rs) {
121+ return rs.one().getInt(0);
122+ }
123+ });
124+ }
125+
51126 private static HostConnectionPool getPool(Session session) {
52- Collection<HostConnectionPool> pools = ((SessionManager) session).pools.values();
127+ Collection<HostConnectionPool> pools = ((SessionManager)session).pools.values();
53128 assertEquals(pools.size(), 1);
54129 return pools.iterator().next();
55130 }
added features/async/README.md +102 −0
@@ -0,0 +1,102 @@
1+## Asynchronous programming
2+
3+The driver exposes an asynchronous API that allows you to write programs
4+in a fully-non blocking manner. Asynchronous methods return instances of
5+Guava's [ListenableFuture], that can be conveniently chained and
6+composed.
7+
8+Here is a short example that opens a session and runs a query
9+asynchronously:
10+
11+```java
12+import com.google.common.util.concurrent.*;
13+
14+ListenableFuture<Session> session = cluster.connectAsync();
15+
16+// Use transform with an AsyncFunction to chain an async operation after another:
17+ListenableFuture<ResultSet> resultSet = Futures.transform(session,
18+ new AsyncFunction<Session, ResultSet>() {
19+ public ListenableFuture<ResultSet> apply(Session session) throws Exception {
20+ return session.executeAsync("select release_version from system.local");
21+ }
22+ });
23+
24+// Use transform with a simple Function to apply a synchronous computation on the result:
25+ListenableFuture<String> version = Futures.transform(resultSet,
26+ new Function<ResultSet, String>() {
27+ public String apply(ResultSet rs) {
28+ return rs.one().getString("release_version");
29+ }
30+ });
31+
32+// Use a callback to perform an action once the future is complete:
33+Futures.addCallback(version, new FutureCallback<String>() {
34+ public void onSuccess(String version) {
35+ System.out.printf("Cassandra version: %s%n", version);
36+ }
37+
38+ public void onFailure(Throwable t) {
39+ System.out.printf("Failed to retrieve the version: %s%n",
40+ t.getMessage());
41+ }
42+});
43+```
44+
45+### Good practices
46+
47+If your callback is slow, consider providing a separate executor.
48+Otherwise the callback might run on one of the driver's I/O threads,
49+blocking I/O operations for other requests while it is running:
50+
51+```java
52+ListenableFuture<String> result = Futures.transform(resultSet,
53+ new Function<ResultSet, String>() {
54+ public String apply(ResultSet rs) {
55+ return someVeryLongComputation(rs);
56+ }
57+ }, myCustomExecutor);
58+```
59+
60+Avoid blocking operations in callbacks, especially if you don't provide
61+a separate executor. This could easily lead to deadlock if the thread
62+that's supposed to complete the blocking call is also the thread that's
63+waiting on it:
64+
65+```java
66+ListenableFuture<ResultSet> resultSet = Futures.transform(session,
67+ new Function<Session, ResultSet>() {
68+ public ResultSet apply(Session session) {
69+ // Synchronous operation in a callback.
70+ // DON'T DO THIS! It might deadlock.
71+ return session.execute("select release_version from system.local");
72+ }
73+ });
74+```
75+
76+### Known limitations
77+
78+There are still a few places where the driver will block internally
79+(mainly for historical reasons):
80+
81+* [Cluster#init][init] performs blocking I/O operations. To avoid
82+ issues, you should create your `Cluster` instances while bootstrapping
83+ your application, and call `init` immediately. If you need to create new
84+ instances at runtime, make sure this does not happen on an I/O thread.
85+* if a connection pool is busy, the driver will block until a connection
86+ becomes available. To avoid this, set
87+ [PoolingOptions.poolTimeoutMillis][setPoolTimeoutMillis] to 0; the
88+ driver will not block, just move to the next host immediately.
89+* if the session is set to a specific keyspace (either at startup or by
90+ issuing a `USE` statement on a running session), the keyspace needs to
91+ be propagated to any newly created connection. This is done when the
92+ connection is first borrowed from the connection pool, and currently
93+ blocks. To avoid any issue, only use a session with no keyspace set
94+ (i.e. created by `Cluster#connect()`). This will be addressed in
95+ [JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893).
96+* trying to read fields from a [query trace] will block if the trace
97+ hasn't been fetched already.
98+
99+[ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained
100+[init]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Cluster.html#init()
101+[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
102+[query trace]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/QueryTrace.html