Elffuss BraidHub

kikocis/java-driver public

Merge pull request #603 from datastax/java1070

JAVA-1070: The Mapper should not prepare queries synchronously.
Changesetafd7556b91bf7685055b80152943b6748f1d763c69e5383a5f2f3481bdd0a276
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-03-07 16:26 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2016-03-07 16:26 +01:00
Parentsdf3d1644b9dd, aa7d4fd67322

Browse the files at this changeset

4 files changed

modified changelog/README.md +1 −0
@@ -31,6 +31,7 @@
3131 - [bug] JAVA-1089: Set LWT made from BuiltStatements to non-idempotent.
3232 - [improvement] JAVA-923: Position idempotent flag on object mapper queries.
3333 - [new feature] JAVA-1019: SchemaBuilder support for CREATE/ALTER/DROP KEYSPACE.
34+- [bug] JAVA-1070: The Mapper should not prepare queries synchronously.
3435
3536 Merged from 2.0 branch:
3637
added driver-mapping/src/main/java/com/datastax/driver/mapping/DriverThrowables.java +45 −0
@@ -0,0 +1,45 @@
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.mapping;
17+
18+import com.datastax.driver.core.exceptions.DriverException;
19+import com.datastax.driver.core.exceptions.DriverInternalError;
20+
21+import java.util.concurrent.ExecutionException;
22+
23+/**
24+ * Copied here from com.datastax.driver.core.DriverThrowables
25+ * because we don't want this class to be public.
26+ */
27+class DriverThrowables {
28+
29+ static RuntimeException propagateCause(ExecutionException e) {
30+ Throwable cause = e.getCause();
31+
32+ if (cause instanceof Error)
33+ throw ((Error) cause);
34+
35+ // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been
36+ // created on the I/O thread receiving the response. Which means that the stacktrace associated
37+ // with said cause will make no mention of the current thread. This is painful for say, finding
38+ // out which execute() statement actually raised the exception. So instead, we re-create the
39+ // exception.
40+ if (cause instanceof DriverException)
41+ throw ((DriverException) cause).copy();
42+ else
43+ throw new DriverInternalError("Unexpected exception thrown", cause);
44+ }
45+}
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +214 −119
@@ -25,12 +25,14 @@
2525 import com.google.common.base.Functions;
2626 import com.google.common.base.Objects;
2727 import com.google.common.base.Preconditions;
28-import com.google.common.util.concurrent.Futures;
29-import com.google.common.util.concurrent.ListenableFuture;
28+import com.google.common.util.concurrent.*;
3029 import org.slf4j.Logger;
3130 import org.slf4j.LoggerFactory;
3231
3332 import java.util.*;
33+import java.util.concurrent.ConcurrentHashMap;
34+import java.util.concurrent.ConcurrentMap;
35+import java.util.concurrent.ExecutionException;
3436
3537 import static com.datastax.driver.mapping.Mapper.Option.Type.SAVE_NULL_FIELDS;
3638 import static com.google.common.base.Preconditions.checkArgument;
@@ -44,6 +46,7 @@
4446 public class Mapper<T> {
4547
4648 private static final Logger logger = LoggerFactory.getLogger(EntityMapper.class);
49+ private static final Function<Object, Void> TO_NULL = Functions.constant(null);
4750
4851 final MappingManager manager;
4952 final ProtocolVersion protocolVersion;
@@ -52,9 +55,7 @@
5255 final TableMetadata tableMetadata;
5356
5457 // Cache prepared statements for each type of query we use.
55- private volatile Map<MapperQueryKey, PreparedStatement> preparedQueries = Collections.emptyMap();
56-
57- private static final Function<Object, Void> NOOP = Functions.constant(null);
58+ private final ConcurrentMap<MapperQueryKey, ListenableFuture<PreparedStatement>> preparedQueries = new ConcurrentHashMap<MapperQueryKey, ListenableFuture<PreparedStatement>>();
5859
5960 private volatile EnumMap<Option.Type, Option> defaultSaveOptions;
6061 private volatile EnumMap<Option.Type, Option> defaultGetOptions;
@@ -103,32 +104,41 @@
103104 return manager.getSession();
104105 }
105106
106- PreparedStatement getPreparedQuery(QueryType type, Set<ColumnMapper<?>> columns, EnumMap<Option.Type, Option> options) {
107-
108- MapperQueryKey pqk = new MapperQueryKey(type, columns, options);
109-
110- PreparedStatement stmt = preparedQueries.get(pqk);
111- if (stmt == null) {
112- synchronized (preparedQueries) {
113- stmt = preparedQueries.get(pqk);
114- if (stmt == null) {
115- String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values());
116- logger.debug("Preparing query {}", queryString);
117- SimpleStatement s = new SimpleStatement(queryString);
118- // all queries generated by the mapper are idempotent
119- s.setIdempotent(true);
120- stmt = session().prepare(s);
121- Map<MapperQueryKey, PreparedStatement> newQueries = new HashMap<MapperQueryKey, PreparedStatement>(preparedQueries);
122- newQueries.put(pqk, stmt);
123- preparedQueries = newQueries;
124- }
107+ ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, Set<ColumnMapper<?>> columns, EnumMap<Option.Type, Option> options) {
108+
109+ final MapperQueryKey pqk = new MapperQueryKey(type, columns, options);
110+ ListenableFuture<PreparedStatement> existingFuture = preparedQueries.get(pqk);
111+ if (existingFuture == null) {
112+ final SettableFuture<PreparedStatement> future = SettableFuture.create();
113+ ListenableFuture<PreparedStatement> old = preparedQueries.putIfAbsent(pqk, future);
114+ if (old != null) {
115+ return old;
116+ } else {
117+ String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values());
118+ logger.debug("Preparing query {}", queryString);
119+ SimpleStatement s = new SimpleStatement(queryString);
120+ // all queries generated by the mapper are idempotent
121+ s.setIdempotent(true);
122+ Futures.addCallback(session().prepareAsync(s), new FutureCallback<PreparedStatement>() {
123+ @Override
124+ public void onSuccess(PreparedStatement stmt) {
125+ future.set(stmt);
126+ }
127+
128+ @Override
129+ public void onFailure(Throwable t) {
130+ future.setException(t);
131+ }
132+ });
133+ return future;
125134 }
135+ } else {
136+ return existingFuture;
126137 }
127- return stmt;
128138 }
129139
130- PreparedStatement getPreparedQuery(QueryType type, EnumMap<Option.Type, Option> options) {
131- return getPreparedQuery(type, Collections.<ColumnMapper<?>>emptySet(), options);
140+ ListenableFuture<PreparedStatement> getPreparedQueryAsync(QueryType type, EnumMap<Option.Type, Option> options) {
141+ return getPreparedQueryAsync(type, Collections.<ColumnMapper<?>>emptySet(), options);
132142 }
133143
134144 /**
@@ -162,7 +172,11 @@
162172 * @return a query that saves {@code entity} (based on it's defined mapping).
163173 */
164174 public Statement saveQuery(T entity) {
165- return saveQuery(entity, this.defaultSaveOptions);
175+ try {
176+ return Uninterruptibles.getUninterruptibly(saveQueryAsync(entity, this.defaultSaveOptions));
177+ } catch (ExecutionException e) {
178+ throw DriverThrowables.propagateCause(e);
179+ }
166180 }
167181
168182 /**
@@ -186,11 +200,15 @@
186200 * @return a query that saves {@code entity} (based on it's defined mapping).
187201 */
188202 public Statement saveQuery(T entity, Option... options) {
189- return saveQuery(entity, toMapWithDefaults(options, this.defaultSaveOptions));
203+ try {
204+ return Uninterruptibles.getUninterruptibly(saveQueryAsync(entity, toMapWithDefaults(options, this.defaultSaveOptions)));
205+ } catch (ExecutionException e) {
206+ throw DriverThrowables.propagateCause(e);
207+ }
190208 }
191209
192- private Statement saveQuery(T entity, EnumMap<Option.Type, Option> options) {
193- Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>();
210+ private ListenableFuture<BoundStatement> saveQueryAsync(T entity, final EnumMap<Option.Type, Option> options) {
211+ final Map<ColumnMapper<?>, Object> values = new HashMap<ColumnMapper<?>, Object>();
194212 boolean saveNullFields = shouldSaveNullFields(options);
195213
196214 for (ColumnMapper<T> cm : mapper.allColumns()) {
@@ -200,23 +218,28 @@
200218 }
201219 }
202220
203- BoundStatement bs = getPreparedQuery(QueryType.SAVE, values.keySet(), options).bind();
204- int i = 0;
205- for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) {
206- DataType type = entry.getKey().getDataType();
207- Object value = entry.getValue();
208- bs.setBytesUnsafe(i++, value == null ? null : type.serialize(value, protocolVersion));
209- }
221+ return Futures.transform(getPreparedQueryAsync(QueryType.SAVE, values.keySet(), options), new Function<PreparedStatement, BoundStatement>() {
222+ @Override
223+ public BoundStatement apply(PreparedStatement input) {
224+ BoundStatement bs = input.bind();
225+ int i = 0;
226+ for (Map.Entry<ColumnMapper<?>, Object> entry : values.entrySet()) {
227+ DataType type = entry.getKey().getDataType();
228+ Object value = entry.getValue();
229+ bs.setBytesUnsafe(i++, value == null ? null : type.serialize(value, protocolVersion));
230+ }
210231
211- if (mapper.writeConsistency != null)
212- bs.setConsistencyLevel(mapper.writeConsistency);
232+ if (mapper.writeConsistency != null)
233+ bs.setConsistencyLevel(mapper.writeConsistency);
213234
214- for (Option opt : options.values()) {
215- opt.checkValidFor(QueryType.SAVE, manager);
216- opt.addToPreparedStatement(bs, i++);
217- }
235+ for (Option opt : options.values()) {
236+ opt.checkValidFor(QueryType.SAVE, manager);
237+ opt.addToPreparedStatement(bs, i++);
238+ }
218239
219- return bs;
240+ return bs;
241+ }
242+ });
220243 }
221244
222245 private static boolean shouldSaveNullFields(EnumMap<Option.Type, Option> options) {
@@ -225,18 +248,22 @@
225248 }
226249
227250 /**
228- * Save an entity mapped by this mapper.
251+ * Saves an entity mapped by this mapper.
229252 * <p/>
230253 * This method is basically equivalent to: {@code getManager().getSession().execute(saveQuery(entity))}.
231254 *
232255 * @param entity the entity to save.
233256 */
234257 public void save(T entity) {
235- session().execute(saveQuery(entity));
258+ try {
259+ Uninterruptibles.getUninterruptibly(saveAsync(entity));
260+ } catch (ExecutionException e) {
261+ throw DriverThrowables.propagateCause(e);
262+ }
236263 }
237264
238265 /**
239- * Save an entity mapped by this mapper and using special options for save.
266+ * Saves an entity mapped by this mapper and using special options for save.
240267 * This method allows you to provide a suite of {@link Option} to include in
241268 * the SAVE query. Options currently supported for SAVE are :
242269 * <ul>
@@ -250,11 +277,15 @@
250277 * @param options the options object specified defining special options when saving.
251278 */
252279 public void save(T entity, Option... options) {
253- session().execute(saveQuery(entity, options));
280+ try {
281+ Uninterruptibles.getUninterruptibly(saveAsync(entity, options));
282+ } catch (ExecutionException e) {
283+ throw DriverThrowables.propagateCause(e);
284+ }
254285 }
255286
256287 /**
257- * Save an entity mapped by this mapper asynchronously.
288+ * Saves an entity mapped by this mapper asynchronously.
258289 * <p/>
259290 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}.
260291 *
@@ -262,7 +293,7 @@
262293 * @return a future on the completion of the save operation.
263294 */
264295 public ListenableFuture<Void> saveAsync(T entity) {
265- return Futures.transform(session().executeAsync(saveQuery(entity)), NOOP);
296+ return submitVoidQueryAsync(saveQueryAsync(entity, this.defaultSaveOptions));
266297 }
267298
268299 /**
@@ -275,7 +306,17 @@
275306 * @return a future on the completion of the save operation.
276307 */
277308 public ListenableFuture<Void> saveAsync(T entity, Option... options) {
278- return Futures.transform(session().executeAsync(saveQuery(entity, options)), NOOP);
309+ return submitVoidQueryAsync(saveQueryAsync(entity, toMapWithDefaults(options, this.defaultSaveOptions)));
310+ }
311+
312+ private ListenableFuture<Void> submitVoidQueryAsync(ListenableFuture<BoundStatement> bsFuture) {
313+ ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() {
314+ @Override
315+ public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception {
316+ return session().executeAsync(bs);
317+ }
318+ });
319+ return Futures.transform(rsFuture, TO_NULL);
279320 }
280321
281322 /**
@@ -304,10 +345,17 @@
304345 * at least one of those values is {@code null}.
305346 */
306347 public Statement getQuery(Object... objects) {
348+ try {
349+ return Uninterruptibles.getUninterruptibly(getQueryAsync(objects));
350+ } catch (ExecutionException e) {
351+ throw DriverThrowables.propagateCause(e);
352+ }
353+ }
354+
355+ private ListenableFuture<BoundStatement> getQueryAsync(Object... objects) {
307356 // Order and duplicates matter for primary keys
308357 List<Object> pks = new ArrayList<Object>();
309358 EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultGetOptions);
310-
311359 for (Object o : objects) {
312360 if (o instanceof Option) {
313361 Option option = (Option) o;
@@ -316,35 +364,38 @@
316364 pks.add(o);
317365 }
318366 }
319- return getQuery(pks, options);
367+ return getQueryAsync(pks, options);
320368 }
321369
322- private Statement getQuery(List<Object> primaryKeys, EnumMap<Option.Type, Option> options) {
323-
370+ private ListenableFuture<BoundStatement> getQueryAsync(final List<Object> primaryKeys, final EnumMap<Option.Type, Option> options) {
324371 if (primaryKeys.size() != mapper.primaryKeySize())
325372 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size()));
326373
327- BoundStatement bs = new MapperBoundStatement(getPreparedQuery(QueryType.GET, options));
328- int i = 0;
329- for (Object value : primaryKeys) {
330- ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
331- if (value == null) {
332- throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
333- }
334- bs.setBytesUnsafe(i++, column.getDataType().serialize(column.toSerializableValue(value), protocolVersion));
335- }
336-
337- if (mapper.readConsistency != null)
338- bs.setConsistencyLevel(mapper.readConsistency);
339-
340- for (Option opt : options.values()) {
341- opt.checkValidFor(QueryType.GET, manager);
342- opt.addToPreparedStatement(bs, i);
343- if (opt.isIncludedInQuery())
344- i++;
345- }
374+ return Futures.transform(getPreparedQueryAsync(QueryType.GET, options), new Function<PreparedStatement, BoundStatement>() {
375+ @Override
376+ public BoundStatement apply(PreparedStatement input) {
377+ BoundStatement bs = new MapperBoundStatement(input);
378+ int i = 0;
379+ for (Object value : primaryKeys) {
380+ ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
381+ if (value == null) {
382+ throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
383+ }
384+ bs.setBytesUnsafe(i++, column.getDataType().serialize(column.toSerializableValue(value), protocolVersion));
385+ }
346386
347- return bs;
387+ if (mapper.readConsistency != null)
388+ bs.setConsistencyLevel(mapper.readConsistency);
389+
390+ for (Option opt : options.values()) {
391+ opt.checkValidFor(QueryType.GET, manager);
392+ opt.addToPreparedStatement(bs, i);
393+ if (opt.isIncludedInQuery())
394+ i++;
395+ }
396+ return bs;
397+ }
398+ });
348399 }
349400
350401 /**
@@ -361,7 +412,11 @@
361412 * at least one of those values is {@code null}.
362413 */
363414 public T get(Object... objects) {
364- return map(session().execute(getQuery(objects))).one();
415+ try {
416+ return Uninterruptibles.getUninterruptibly(getAsync(objects));
417+ } catch (ExecutionException e) {
418+ throw DriverThrowables.propagateCause(e);
419+ }
365420 }
366421
367422 /**
@@ -378,8 +433,15 @@
378433 * the number of columns composing the PRIMARY KEY of the mapped class, or if
379434 * at least one of those values is {@code null}.
380435 */
381- public ListenableFuture<T> getAsync(Object... objects) {
382- return Futures.transform(session().executeAsync(getQuery(objects)), mapOneFunction);
436+ public ListenableFuture<T> getAsync(final Object... objects) {
437+ ListenableFuture<BoundStatement> bsFuture = getQueryAsync(objects);
438+ ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() {
439+ @Override
440+ public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception {
441+ return session().executeAsync(bs);
442+ }
443+ });
444+ return Futures.transform(rsFuture, mapOneFunction);
383445 }
384446
385447 /**
@@ -411,12 +473,11 @@
411473 * provided USING options.
412474 */
413475 public Statement deleteQuery(T entity, Option... options) {
414- List<Object> pks = new ArrayList<Object>();
415- for (int i = 0; i < mapper.primaryKeySize(); i++) {
416- pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
476+ try {
477+ return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions)));
478+ } catch (ExecutionException e) {
479+ throw DriverThrowables.propagateCause(e);
417480 }
418-
419- return deleteQuery(pks, toMapWithDefaults(options, defaultDeleteOptions));
420481 }
421482
422483 /**
@@ -435,12 +496,11 @@
435496 * @return a query that delete {@code entity} (based on it's defined mapping).
436497 */
437498 public Statement deleteQuery(T entity) {
438- List<Object> pks = new ArrayList<Object>();
439- for (int i = 0; i < mapper.primaryKeySize(); i++) {
440- pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
499+ try {
500+ return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, defaultDeleteOptions));
501+ } catch (ExecutionException e) {
502+ throw DriverThrowables.propagateCause(e);
441503 }
442-
443- return deleteQuery(pks, defaultDeleteOptions);
444504 }
445505
446506 /**
@@ -475,10 +535,25 @@
475535 * at least one of those values is {@code null}.
476536 */
477537 public Statement deleteQuery(Object... objects) {
538+ try {
539+ return Uninterruptibles.getUninterruptibly(deleteQueryAsync(objects));
540+ } catch (ExecutionException e) {
541+ throw DriverThrowables.propagateCause(e);
542+ }
543+ }
544+
545+ private ListenableFuture<BoundStatement> deleteQueryAsync(T entity, EnumMap<Option.Type, Option> options) {
546+ List<Object> pks = new ArrayList<Object>();
547+ for (int i = 0; i < mapper.primaryKeySize(); i++) {
548+ pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
549+ }
550+ return deleteQueryAsync(pks, options);
551+ }
552+
553+ private ListenableFuture<BoundStatement> deleteQueryAsync(Object... objects) {
478554 // Order and duplicates matter for primary keys
479555 List<Object> pks = new ArrayList<Object>();
480556 EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultDeleteOptions);
481-
482557 for (Object o : objects) {
483558 if (o instanceof Option) {
484559 Option option = (Option) o;
@@ -487,36 +562,40 @@
487562 pks.add(o);
488563 }
489564 }
490- return deleteQuery(pks, options);
565+ return deleteQueryAsync(pks, options);
491566 }
492567
493- private Statement deleteQuery(List<Object> primaryKey, EnumMap<Option.Type, Option> options) {
568+ private ListenableFuture<BoundStatement> deleteQueryAsync(final List<Object> primaryKey, final EnumMap<Option.Type, Option> options) {
494569 if (primaryKey.size() != mapper.primaryKeySize())
495570 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.size()));
496571
497- BoundStatement bs = getPreparedQuery(QueryType.DEL, options).bind();
498-
499- if (mapper.writeConsistency != null)
500- bs.setConsistencyLevel(mapper.writeConsistency);
501-
502- int i = 0;
503- for (Option opt : options.values()) {
504- opt.checkValidFor(QueryType.DEL, manager);
505- opt.addToPreparedStatement(bs, i);
506- if (opt.isIncludedInQuery())
507- i++;
508- }
572+ return Futures.transform(getPreparedQueryAsync(QueryType.DEL, options), new Function<PreparedStatement, BoundStatement>() {
573+ @Override
574+ public BoundStatement apply(PreparedStatement input) {
575+ BoundStatement bs = input.bind();
576+ if (mapper.writeConsistency != null)
577+ bs.setConsistencyLevel(mapper.writeConsistency);
578+
579+ int i = 0;
580+ for (Option opt : options.values()) {
581+ opt.checkValidFor(QueryType.DEL, manager);
582+ opt.addToPreparedStatement(bs, i);
583+ if (opt.isIncludedInQuery())
584+ i++;
585+ }
509586
510- int columnNumber = 0;
511- for (Object value : primaryKey) {
512- ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber);
513- if (value == null) {
514- throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
587+ int columnNumber = 0;
588+ for (Object value : primaryKey) {
589+ ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber);
590+ if (value == null) {
591+ throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
592+ }
593+ bs.setBytesUnsafe(i++, column.getDataType().serialize(column.toSerializableValue(value), protocolVersion));
594+ columnNumber++;
595+ }
596+ return bs;
515597 }
516- bs.setBytesUnsafe(i++, column.getDataType().serialize(column.toSerializableValue(value), protocolVersion));
517- columnNumber++;
518- }
519- return bs;
598+ });
520599 }
521600
522601 /**
@@ -527,7 +606,11 @@
527606 * @param entity the entity to delete.
528607 */
529608 public void delete(T entity) {
530- session().execute(deleteQuery(entity));
609+ try {
610+ Uninterruptibles.getUninterruptibly(deleteAsync(entity));
611+ } catch (ExecutionException e) {
612+ throw DriverThrowables.propagateCause(e);
613+ }
531614 }
532615
533616 /**
@@ -539,7 +622,11 @@
539622 * @param options the options to add to the DELETE query.
540623 */
541624 public void delete(T entity, Option... options) {
542- session().execute(deleteQuery(entity, options));
625+ try {
626+ Uninterruptibles.getUninterruptibly(deleteAsync(entity, options));
627+ } catch (ExecutionException e) {
628+ throw DriverThrowables.propagateCause(e);
629+ }
543630 }
544631
545632 /**
@@ -551,7 +638,7 @@
551638 * @return a future on the completion of the deletion.
552639 */
553640 public ListenableFuture<Void> deleteAsync(T entity) {
554- return Futures.transform(session().executeAsync(deleteQuery(entity)), NOOP);
641+ return submitVoidQueryAsync(deleteQueryAsync(entity, defaultDeleteOptions));
555642 }
556643
557644 /**
@@ -564,7 +651,7 @@
564651 * @return a future on the completion of the deletion.
565652 */
566653 public ListenableFuture<Void> deleteAsync(T entity, Option... options) {
567- return Futures.transform(session().executeAsync(deleteQuery(entity, options)), NOOP);
654+ return submitVoidQueryAsync(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions)));
568655 }
569656
570657 /**
@@ -581,7 +668,11 @@
581668 * at least one of those values is {@code null}.
582669 */
583670 public void delete(Object... objects) {
584- session().execute(deleteQuery(objects));
671+ try {
672+ Uninterruptibles.getUninterruptibly(deleteAsync(objects));
673+ } catch (ExecutionException e) {
674+ throw DriverThrowables.propagateCause(e);
675+ }
585676 }
586677
587678 /**
@@ -598,10 +689,14 @@
598689 * at least one of those values is {@code null}.
599690 */
600691 public ListenableFuture<Void> deleteAsync(Object... objects) {
601- return Futures.transform(session().executeAsync(deleteQuery(objects)), NOOP);
692+ return submitVoidQueryAsync(deleteQueryAsync(objects));
602693 }
603694
604695 /**
696+ * Creates a query to fetch entity given its PRIMARY KEY.
697+ * <p/>
698+ * <p/>
699+ * /**
605700 * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
606701 * <p/>
607702 * If the query was user-generated (that is, passed directly to {@code session.execute()} or configured with
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperAsyncTest.java +186 −0
@@ -0,0 +1,186 @@
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.mapping;
17+
18+import com.datastax.driver.core.CCMTestsSupport;
19+import com.datastax.driver.core.Cluster;
20+import com.datastax.driver.core.Session;
21+import com.datastax.driver.core.utils.MoreFutures.SuccessCallback;
22+import com.datastax.driver.core.utils.UUIDs;
23+import com.datastax.driver.mapping.annotations.Column;
24+import com.datastax.driver.mapping.annotations.PartitionKey;
25+import com.datastax.driver.mapping.annotations.Table;
26+import com.google.common.base.Function;
27+import com.google.common.base.Objects;
28+import com.google.common.util.concurrent.Futures;
29+import com.google.common.util.concurrent.ListenableFuture;
30+import com.google.common.util.concurrent.Uninterruptibles;
31+import org.testng.annotations.Test;
32+
33+import java.util.UUID;
34+import java.util.concurrent.CountDownLatch;
35+
36+import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
37+import static java.util.concurrent.TimeUnit.MINUTES;
38+import static org.testng.Assert.fail;
39+
40+/**
41+ * Basic tests for the mapping module.
42+ */
43+@SuppressWarnings("unused")
44+public class MapperAsyncTest extends CCMTestsSupport {
45+
46+ private static final String KEYSPACE = "mapper_async_test_ks";
47+
48+ private final User paul = new User("Paul", "paul@yahoo.com");
49+
50+ @Override
51+ public void onTestContextInitialized() {
52+ execute(
53+ String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, KEYSPACE, 1),
54+ String.format("CREATE TABLE %s.users (user_id uuid PRIMARY KEY, name text, email text)", KEYSPACE)
55+ );
56+ }
57+
58+ /**
59+ * Validates that when using save, get and deleteAsync using the same executor as the caller that the driver
60+ * does not block indefinitely in a netty worker thread.
61+ *
62+ * @jira_ticket JAVA-1070
63+ * @test_category queries:async
64+ * @test_category object_mapper
65+ */
66+ @Test(groups = "short")
67+ public void should_get_query_async_without_blocking() {
68+
69+ final CountDownLatch latch = new CountDownLatch(1);
70+
71+ // create a second cluster to perform everything asynchronously,
72+ // including session initialization
73+ Cluster cluster2 = register(
74+ createClusterBuilderNoDebouncing()
75+ .addContactPoints(getContactPoints())
76+ .withPort(ccm().getBinaryPort())
77+ .build());
78+
79+ ListenableFuture<MappingManager> mappingManagerFuture = Futures.transform(
80+ cluster2.connectAsync(),
81+ new Function<Session, MappingManager>() {
82+ @Override
83+ public MappingManager apply(Session session) {
84+ return new MappingManager(session);
85+ }
86+ });
87+
88+ Futures.addCallback(mappingManagerFuture, new SuccessCallback<MappingManager>() {
89+
90+ @Override
91+ public void onSuccess(MappingManager manager) {
92+
93+ final Mapper<User> mapper = manager.mapper(User.class);
94+ ListenableFuture<Void> saveFuture = mapper.saveAsync(paul);
95+ Futures.addCallback(saveFuture, new SuccessCallback<Void>() {
96+
97+ @Override
98+ public void onSuccess(Void result) {
99+ ListenableFuture<User> getFuture = mapper.getAsync(paul.getUserId());
100+ Futures.addCallback(getFuture, new SuccessCallback<User>() {
101+
102+ @Override
103+ public void onSuccess(User paul) {
104+
105+ Futures.addCallback(mapper.deleteAsync(paul), new SuccessCallback<Void>() {
106+ @Override
107+ public void onSuccess(Void result) {
108+ latch.countDown();
109+ }
110+ });
111+ }
112+ });
113+ }
114+ });
115+ }
116+ });
117+
118+ try {
119+ Uninterruptibles.awaitUninterruptibly(latch, 5, MINUTES);
120+ } catch (Exception e) {
121+ fail("Operation did not complete normally within 5 minutes");
122+ }
123+ }
124+
125+ @Table(name = "users", keyspace = KEYSPACE)
126+ public static class User {
127+
128+ @PartitionKey
129+ @Column(name = "user_id")
130+ private UUID userId;
131+
132+ private String name;
133+
134+ private String email;
135+
136+ public User() {
137+ }
138+
139+ public User(String name, String email) {
140+ this.userId = UUIDs.random();
141+ this.name = name;
142+ this.email = email;
143+ }
144+
145+ public UUID getUserId() {
146+ return userId;
147+ }
148+
149+ public void setUserId(UUID userId) {
150+ this.userId = userId;
151+ }
152+
153+ public String getName() {
154+ return name;
155+ }
156+
157+ public void setName(String name) {
158+ this.name = name;
159+ }
160+
161+ public String getEmail() {
162+ return email;
163+ }
164+
165+ public void setEmail(String email) {
166+ this.email = email;
167+ }
168+
169+ @Override
170+ public boolean equals(Object other) {
171+ if (other == null || other.getClass() != this.getClass())
172+ return false;
173+
174+ User that = (User) other;
175+ return Objects.equal(userId, that.userId)
176+ && Objects.equal(name, that.name)
177+ && Objects.equal(email, that.email);
178+ }
179+
180+ @Override
181+ public int hashCode() {
182+ return Objects.hashCode(userId, name, email);
183+ }
184+ }
185+
186+}