Elffuss BraidHub

kikocis/java-driver public

3.1.x · 5.3 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/3.0/com/datastax/driver/core/ResultSet.html#getAvailableWithoutFetching--
55[fetchMoreResults]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSet.html#fetchMoreResults--
56
57```java
58Statement statement = new SimpleStatement("select * from foo").setFetchSize(20);
59ListenableFuture<ResultSet> future = Futures.transform(
60 session.executeAsync(statement),
61 iterate(1));
62
63private static AsyncFunction<ResultSet, ResultSet> iterate(final int page) {
64 return new AsyncFunction<ResultSet, ResultSet>() {
65 @Override
66 public ListenableFuture<ResultSet> apply(ResultSet rs) throws Exception {
67
68 // How far we can go without triggering the blocking fetch:
69 int remainingInPage = rs.getAvailableWithoutFetching();
70
71 System.out.printf("Starting page %d (%d rows)%n", page, remainingInPage);
72
73 for (Row row : rs) {
74 System.out.printf("[page %d - %d] row = %s%n", page, remainingInPage, row);
75 if (--remainingInPage == 0)
76 break;
77 }
78 System.out.printf("Done page %d%n", page);
79
80 boolean wasLastPage = rs.getExecutionInfo().getPagingState() == null;
81 if (wasLastPage) {
82 System.out.println("Done iterating");
83 return Futures.immediateFuture(rs);
84 } else {
85 ListenableFuture<ResultSet> future = rs.fetchMoreResults();
86 return Futures.transform(future, iterate(page + 1));
87 }
88 }
89 };
90}
91```
92
93### Good practices
94
95If your callback is slow, consider providing a separate executor.
96Otherwise the callback might run on one of the driver's I/O threads,
97blocking I/O operations for other requests while it is running:
98
99```java
100ListenableFuture<String> result = Futures.transform(resultSet,
101 new Function<ResultSet, String>() {
102 public String apply(ResultSet rs) {
103 return someVeryLongComputation(rs);
104 }
105 }, myCustomExecutor);
106```
107
108Avoid blocking operations in callbacks, especially if you don't provide
109a separate executor. This could easily lead to deadlock if the thread
110that's supposed to complete the blocking call is also the thread that's
111waiting on it:
112
113```java
114ListenableFuture<ResultSet> resultSet = Futures.transform(session,
115 new Function<Session, ResultSet>() {
116 public ResultSet apply(Session session) {
117 // Synchronous operation in a callback.
118 // DON'T DO THIS! It might deadlock.
119 return session.execute("select release_version from system.local");
120 }
121 });
122```
123
124### Known limitations
125
126There are still a few places where the driver will block internally
127(mainly for historical reasons):
128
129* [Cluster#init][init] performs blocking I/O operations. To avoid
130 issues, you should create your `Cluster` instances while bootstrapping
131 your application, and call `init` immediately. If you need to create new
132 instances at runtime, make sure this does not happen on an I/O thread.
133* trying to read fields from a [query trace] will block if the trace
134 hasn't been fetched already.
135
136[ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained
137[init]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Cluster.html#init--
138[query trace]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryTrace.html