Elffuss BraidHub

kikocis/java-driver public

5cd205e3f802 · 6.6 KiBRenderedRawPermalink
1## Asynchronous programming
2
3The driver exposes an asynchronous API that allows you to write programs
4in a fully-non blocking manner. Asynchronous methods return instances of
5Guava's [ListenableFuture], that can be conveniently chained and
6composed.
7
8Here is a short example that opens a session and runs a query
9asynchronously:
10
11```java
12import com.google.common.util.concurrent.*;
13
14ListenableFuture<Session> session = cluster.connectAsync();
15
16// Use transform with an AsyncFunction to chain an async operation after another:
17ListenableFuture<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:
25ListenableFuture<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:
33Futures.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### Async paging
46
47If you consume a `ResultSet` in a callback, be aware that iterating the
48rows will trigger synchronous queries as you page through the results.
49To avoid this, use [getAvailableWithoutFetching] to limit the iteration
50to the current page, and [fetchMoreResults] to get a future to the next
51page (see also the section on [paging](../paging/)).
52Here is a full example:
53
54[getAvailableWithoutFetching]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSet.html#getAvailableWithoutFetching--
55[fetchMoreResults]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/ResultSet.html#fetchMoreResults--
56
57```java
58Statement statement = new SimpleStatement("select * from foo").setFetchSize(20);
59ListenableFuture<Void> future = Futures.transform(
60 session.executeAsync(statement),
61 iterateFirst());
62
63// Unfortunately we have to special-case for the first page because the signatures of the
64// futures differ.
65// In 3.0, fetchMoreResults() will return a Future<ResultSet> to avoid this.
66private static AsyncFunction<ResultSet, Void> iterateFirst() {
67 return new AsyncFunction<ResultSet, Void>() {
68 @Override
69 public ListenableFuture<Void> apply(ResultSet rs) throws Exception {
70 return iterate(rs, 1).apply(null);
71 }
72 };
73}
74
75private static AsyncFunction<Void, Void> iterate(final ResultSet rs, final int page) {
76 return new AsyncFunction<Void, Void>() {
77 @Override
78 public ListenableFuture<Void> apply(Void v) throws Exception {
79
80 // How far we can go without triggering the blocking fetch:
81 int remainingInPage = rs.getAvailableWithoutFetching();
82
83 System.out.printf("Starting page %d (%d rows)%n", page, remainingInPage);
84
85 for (Row row : rs) {
86 System.out.printf("[page %d - %d] row = %s%n", page, remainingInPage, row);
87 if (--remainingInPage == 0)
88 break;
89 }
90 System.out.printf("Done page %d%n", page);
91
92 boolean wasLastPage = rs.getExecutionInfo().getPagingState() == null;
93 if (wasLastPage) {
94 System.out.println("Done iterating");
95 return Futures.immediateFuture(null);
96 } else {
97 ListenableFuture<Void> future = rs.fetchMoreResults();
98 return Futures.transform(future, iterate(rs, page + 1));
99 }
100 }
101 };
102}
103```
104
105### Good practices
106
107If your callback is slow, consider providing a separate executor.
108Otherwise the callback might run on one of the driver's I/O threads,
109blocking I/O operations for other requests while it is running:
110
111```java
112ListenableFuture<String> result = Futures.transform(resultSet,
113 new Function<ResultSet, String>() {
114 public String apply(ResultSet rs) {
115 return someVeryLongComputation(rs);
116 }
117 }, myCustomExecutor);
118```
119
120Avoid blocking operations in callbacks, especially if you don't provide
121a separate executor. This could easily lead to deadlock if the thread
122that's supposed to complete the blocking call is also the thread that's
123waiting on it:
124
125```java
126ListenableFuture<ResultSet> resultSet = Futures.transform(session,
127 new Function<Session, ResultSet>() {
128 public ResultSet apply(Session session) {
129 // Synchronous operation in a callback.
130 // DON'T DO THIS! It might deadlock.
131 return session.execute("select release_version from system.local");
132 }
133 });
134```
135
136### Known limitations
137
138There are still a few places where the driver will block internally
139(mainly for historical reasons):
140
141* [Cluster#init][init] performs blocking I/O operations. To avoid
142 issues, you should create your `Cluster` instances while bootstrapping
143 your application, and call `init` immediately. If you need to create new
144 instances at runtime, make sure this does not happen on an I/O thread.
145* if a connection pool is busy, the driver will block until a connection
146 becomes available. To avoid this, set
147 [PoolingOptions.poolTimeoutMillis][setPoolTimeoutMillis] to 0; the
148 driver will not block, just move to the next host immediately.
149* if the session is set to a specific keyspace (either at startup or by
150 issuing a `USE` statement on a running session), the keyspace needs to
151 be propagated to any newly created connection. This is done when the
152 connection is first borrowed from the connection pool, and currently
153 blocks. To avoid any issue, only use a session with no keyspace set
154 (i.e. created by `Cluster#connect()`). This will be addressed in
155 [JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893).
156* trying to read fields from a [query trace] will block if the trace
157 hasn't been fetched already.
158
159[ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained
160[init]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.html#init()
161[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
162[query trace]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryTrace.html