Elffuss BraidHub

kikocis/java-driver public

JAVA-1070: The Mapper should not prepare queries synchronously.

(cherry picked from 2.1)
Changeseta8f33563abe02bf8eb92a4fd5ba6b0c5758de970251fa68339ea9d7cc1b4e9a5
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-03-07 16:26 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2016-04-01 11:35 +02:00
Parents4a433a1ccc27

Browse the files at this changeset

4 files changed

modified changelog/README.md +1 −0
@@ -15,6 +15,7 @@
1515 - [bug] JAVA-1064: getTable create statement doesn't properly handle quotes in primary key.
1616 - [bug] JAVA-1089: Set LWT made from BuiltStatements to non-idempotent.
1717 - [improvement] JAVA-923: Position idempotent flag on object mapper queries.
18+- [bug] JAVA-1070: The Mapper should not prepare queries synchronously.
1819
1920
2021 ### 3.0.0
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- ColumnMapper<?> mapper = entry.getKey();
207- Object value = entry.getValue();
208- setObject(bs, i++, value, mapper);
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+ ColumnMapper<?> mapper = entry.getKey();
228+ Object value = entry.getValue();
229+ setObject(bs, i++, value, mapper);
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) {
@@ -233,18 +256,22 @@
233256 }
234257
235258 /**
236- * Save an entity mapped by this mapper.
259+ * Saves an entity mapped by this mapper.
237260 * <p/>
238261 * This method is basically equivalent to: {@code getManager().getSession().execute(saveQuery(entity))}.
239262 *
240263 * @param entity the entity to save.
241264 */
242265 public void save(T entity) {
243- session().execute(saveQuery(entity));
266+ try {
267+ Uninterruptibles.getUninterruptibly(saveAsync(entity));
268+ } catch (ExecutionException e) {
269+ throw DriverThrowables.propagateCause(e);
270+ }
244271 }
245272
246273 /**
247- * Save an entity mapped by this mapper and using special options for save.
274+ * Saves an entity mapped by this mapper and using special options for save.
248275 * This method allows you to provide a suite of {@link Option} to include in
249276 * the SAVE query. Options currently supported for SAVE are :
250277 * <ul>
@@ -258,11 +285,15 @@
258285 * @param options the options object specified defining special options when saving.
259286 */
260287 public void save(T entity, Option... options) {
261- session().execute(saveQuery(entity, options));
288+ try {
289+ Uninterruptibles.getUninterruptibly(saveAsync(entity, options));
290+ } catch (ExecutionException e) {
291+ throw DriverThrowables.propagateCause(e);
292+ }
262293 }
263294
264295 /**
265- * Save an entity mapped by this mapper asynchronously.
296+ * Saves an entity mapped by this mapper asynchronously.
266297 * <p/>
267298 * This method is basically equivalent to: {@code getManager().getSession().executeAsync(saveQuery(entity))}.
268299 *
@@ -270,7 +301,7 @@
270301 * @return a future on the completion of the save operation.
271302 */
272303 public ListenableFuture<Void> saveAsync(T entity) {
273- return Futures.transform(session().executeAsync(saveQuery(entity)), NOOP);
304+ return submitVoidQueryAsync(saveQueryAsync(entity, this.defaultSaveOptions));
274305 }
275306
276307 /**
@@ -283,7 +314,17 @@
283314 * @return a future on the completion of the save operation.
284315 */
285316 public ListenableFuture<Void> saveAsync(T entity, Option... options) {
286- return Futures.transform(session().executeAsync(saveQuery(entity, options)), NOOP);
317+ return submitVoidQueryAsync(saveQueryAsync(entity, toMapWithDefaults(options, this.defaultSaveOptions)));
318+ }
319+
320+ private ListenableFuture<Void> submitVoidQueryAsync(ListenableFuture<BoundStatement> bsFuture) {
321+ ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() {
322+ @Override
323+ public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception {
324+ return session().executeAsync(bs);
325+ }
326+ });
327+ return Futures.transform(rsFuture, TO_NULL);
287328 }
288329
289330 /**
@@ -312,10 +353,17 @@
312353 * at least one of those values is {@code null}.
313354 */
314355 public Statement getQuery(Object... objects) {
356+ try {
357+ return Uninterruptibles.getUninterruptibly(getQueryAsync(objects));
358+ } catch (ExecutionException e) {
359+ throw DriverThrowables.propagateCause(e);
360+ }
361+ }
362+
363+ private ListenableFuture<BoundStatement> getQueryAsync(Object... objects) {
315364 // Order and duplicates matter for primary keys
316365 List<Object> pks = new ArrayList<Object>();
317366 EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultGetOptions);
318-
319367 for (Object o : objects) {
320368 if (o instanceof Option) {
321369 Option option = (Option) o;
@@ -324,35 +372,38 @@
324372 pks.add(o);
325373 }
326374 }
327- return getQuery(pks, options);
375+ return getQueryAsync(pks, options);
328376 }
329377
330- private Statement getQuery(List<Object> primaryKeys, EnumMap<Option.Type, Option> options) {
331-
378+ private ListenableFuture<BoundStatement> getQueryAsync(final List<Object> primaryKeys, final EnumMap<Option.Type, Option> options) {
332379 if (primaryKeys.size() != mapper.primaryKeySize())
333380 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKeys.size()));
334381
335- BoundStatement bs = new MapperBoundStatement(getPreparedQuery(QueryType.GET, options));
336- int i = 0;
337- for (Object value : primaryKeys) {
338- ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
339- if (value == null) {
340- throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
341- }
342- setObject(bs, i++, value, column);
343- }
344-
345- if (mapper.readConsistency != null)
346- bs.setConsistencyLevel(mapper.readConsistency);
347-
348- for (Option opt : options.values()) {
349- opt.checkValidFor(QueryType.GET, manager);
350- opt.addToPreparedStatement(bs, i);
351- if (opt.isIncludedInQuery())
352- i++;
353- }
382+ return Futures.transform(getPreparedQueryAsync(QueryType.GET, options), new Function<PreparedStatement, BoundStatement>() {
383+ @Override
384+ public BoundStatement apply(PreparedStatement input) {
385+ BoundStatement bs = new MapperBoundStatement(input);
386+ int i = 0;
387+ for (Object value : primaryKeys) {
388+ ColumnMapper<T> column = mapper.getPrimaryKeyColumn(i);
389+ if (value == null) {
390+ throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
391+ }
392+ setObject(bs, i++, value, column);
393+ }
354394
355- return bs;
395+ if (mapper.readConsistency != null)
396+ bs.setConsistencyLevel(mapper.readConsistency);
397+
398+ for (Option opt : options.values()) {
399+ opt.checkValidFor(QueryType.GET, manager);
400+ opt.addToPreparedStatement(bs, i);
401+ if (opt.isIncludedInQuery())
402+ i++;
403+ }
404+ return bs;
405+ }
406+ });
356407 }
357408
358409 /**
@@ -369,7 +420,11 @@
369420 * at least one of those values is {@code null}.
370421 */
371422 public T get(Object... objects) {
372- return map(session().execute(getQuery(objects))).one();
423+ try {
424+ return Uninterruptibles.getUninterruptibly(getAsync(objects));
425+ } catch (ExecutionException e) {
426+ throw DriverThrowables.propagateCause(e);
427+ }
373428 }
374429
375430 /**
@@ -386,8 +441,15 @@
386441 * the number of columns composing the PRIMARY KEY of the mapped class, or if
387442 * at least one of those values is {@code null}.
388443 */
389- public ListenableFuture<T> getAsync(Object... objects) {
390- return Futures.transform(session().executeAsync(getQuery(objects)), mapOneFunction);
444+ public ListenableFuture<T> getAsync(final Object... objects) {
445+ ListenableFuture<BoundStatement> bsFuture = getQueryAsync(objects);
446+ ListenableFuture<ResultSet> rsFuture = Futures.transform(bsFuture, new AsyncFunction<BoundStatement, ResultSet>() {
447+ @Override
448+ public ListenableFuture<ResultSet> apply(BoundStatement bs) throws Exception {
449+ return session().executeAsync(bs);
450+ }
451+ });
452+ return Futures.transform(rsFuture, mapOneFunction);
391453 }
392454
393455 /**
@@ -419,12 +481,11 @@
419481 * provided USING options.
420482 */
421483 public Statement deleteQuery(T entity, Option... options) {
422- List<Object> pks = new ArrayList<Object>();
423- for (int i = 0; i < mapper.primaryKeySize(); i++) {
424- pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
484+ try {
485+ return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions)));
486+ } catch (ExecutionException e) {
487+ throw DriverThrowables.propagateCause(e);
425488 }
426-
427- return deleteQuery(pks, toMapWithDefaults(options, defaultDeleteOptions));
428489 }
429490
430491 /**
@@ -443,12 +504,11 @@
443504 * @return a query that delete {@code entity} (based on it's defined mapping).
444505 */
445506 public Statement deleteQuery(T entity) {
446- List<Object> pks = new ArrayList<Object>();
447- for (int i = 0; i < mapper.primaryKeySize(); i++) {
448- pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
507+ try {
508+ return Uninterruptibles.getUninterruptibly(deleteQueryAsync(entity, defaultDeleteOptions));
509+ } catch (ExecutionException e) {
510+ throw DriverThrowables.propagateCause(e);
449511 }
450-
451- return deleteQuery(pks, defaultDeleteOptions);
452512 }
453513
454514 /**
@@ -483,10 +543,25 @@
483543 * at least one of those values is {@code null}.
484544 */
485545 public Statement deleteQuery(Object... objects) {
546+ try {
547+ return Uninterruptibles.getUninterruptibly(deleteQueryAsync(objects));
548+ } catch (ExecutionException e) {
549+ throw DriverThrowables.propagateCause(e);
550+ }
551+ }
552+
553+ private ListenableFuture<BoundStatement> deleteQueryAsync(T entity, EnumMap<Option.Type, Option> options) {
554+ List<Object> pks = new ArrayList<Object>();
555+ for (int i = 0; i < mapper.primaryKeySize(); i++) {
556+ pks.add(mapper.getPrimaryKeyColumn(i).getValue(entity));
557+ }
558+ return deleteQueryAsync(pks, options);
559+ }
560+
561+ private ListenableFuture<BoundStatement> deleteQueryAsync(Object... objects) {
486562 // Order and duplicates matter for primary keys
487563 List<Object> pks = new ArrayList<Object>();
488564 EnumMap<Option.Type, Option> options = new EnumMap<Option.Type, Option>(defaultDeleteOptions);
489-
490565 for (Object o : objects) {
491566 if (o instanceof Option) {
492567 Option option = (Option) o;
@@ -495,36 +570,40 @@
495570 pks.add(o);
496571 }
497572 }
498- return deleteQuery(pks, options);
573+ return deleteQueryAsync(pks, options);
499574 }
500575
501- private Statement deleteQuery(List<Object> primaryKey, EnumMap<Option.Type, Option> options) {
576+ private ListenableFuture<BoundStatement> deleteQueryAsync(final List<Object> primaryKey, final EnumMap<Option.Type, Option> options) {
502577 if (primaryKey.size() != mapper.primaryKeySize())
503578 throw new IllegalArgumentException(String.format("Invalid number of PRIMARY KEY columns provided, %d expected but got %d", mapper.primaryKeySize(), primaryKey.size()));
504579
505- BoundStatement bs = getPreparedQuery(QueryType.DEL, options).bind();
506-
507- if (mapper.writeConsistency != null)
508- bs.setConsistencyLevel(mapper.writeConsistency);
509-
510- int i = 0;
511- for (Option opt : options.values()) {
512- opt.checkValidFor(QueryType.DEL, manager);
513- opt.addToPreparedStatement(bs, i);
514- if (opt.isIncludedInQuery())
515- i++;
516- }
580+ return Futures.transform(getPreparedQueryAsync(QueryType.DEL, options), new Function<PreparedStatement, BoundStatement>() {
581+ @Override
582+ public BoundStatement apply(PreparedStatement input) {
583+ BoundStatement bs = input.bind();
584+ if (mapper.writeConsistency != null)
585+ bs.setConsistencyLevel(mapper.writeConsistency);
586+
587+ int i = 0;
588+ for (Option opt : options.values()) {
589+ opt.checkValidFor(QueryType.DEL, manager);
590+ opt.addToPreparedStatement(bs, i);
591+ if (opt.isIncludedInQuery())
592+ i++;
593+ }
517594
518- int columnNumber = 0;
519- for (Object value : primaryKey) {
520- ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber);
521- if (value == null) {
522- throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
595+ int columnNumber = 0;
596+ for (Object value : primaryKey) {
597+ ColumnMapper<T> column = mapper.getPrimaryKeyColumn(columnNumber);
598+ if (value == null) {
599+ throw new IllegalArgumentException(String.format("Invalid null value for PRIMARY KEY column %s (argument %d)", column.getColumnName(), i));
600+ }
601+ setObject(bs, i++, value, column);
602+ columnNumber++;
603+ }
604+ return bs;
523605 }
524- setObject(bs, i++, value, column);
525- columnNumber++;
526- }
527- return bs;
606+ });
528607 }
529608
530609 /**
@@ -535,7 +614,11 @@
535614 * @param entity the entity to delete.
536615 */
537616 public void delete(T entity) {
538- session().execute(deleteQuery(entity));
617+ try {
618+ Uninterruptibles.getUninterruptibly(deleteAsync(entity));
619+ } catch (ExecutionException e) {
620+ throw DriverThrowables.propagateCause(e);
621+ }
539622 }
540623
541624 /**
@@ -547,7 +630,11 @@
547630 * @param options the options to add to the DELETE query.
548631 */
549632 public void delete(T entity, Option... options) {
550- session().execute(deleteQuery(entity, options));
633+ try {
634+ Uninterruptibles.getUninterruptibly(deleteAsync(entity, options));
635+ } catch (ExecutionException e) {
636+ throw DriverThrowables.propagateCause(e);
637+ }
551638 }
552639
553640 /**
@@ -559,7 +646,7 @@
559646 * @return a future on the completion of the deletion.
560647 */
561648 public ListenableFuture<Void> deleteAsync(T entity) {
562- return Futures.transform(session().executeAsync(deleteQuery(entity)), NOOP);
649+ return submitVoidQueryAsync(deleteQueryAsync(entity, defaultDeleteOptions));
563650 }
564651
565652 /**
@@ -572,7 +659,7 @@
572659 * @return a future on the completion of the deletion.
573660 */
574661 public ListenableFuture<Void> deleteAsync(T entity, Option... options) {
575- return Futures.transform(session().executeAsync(deleteQuery(entity, options)), NOOP);
662+ return submitVoidQueryAsync(deleteQueryAsync(entity, toMapWithDefaults(options, defaultDeleteOptions)));
576663 }
577664
578665 /**
@@ -589,7 +676,11 @@
589676 * at least one of those values is {@code null}.
590677 */
591678 public void delete(Object... objects) {
592- session().execute(deleteQuery(objects));
679+ try {
680+ Uninterruptibles.getUninterruptibly(deleteAsync(objects));
681+ } catch (ExecutionException e) {
682+ throw DriverThrowables.propagateCause(e);
683+ }
593684 }
594685
595686 /**
@@ -606,10 +697,14 @@
606697 * at least one of those values is {@code null}.
607698 */
608699 public ListenableFuture<Void> deleteAsync(Object... objects) {
609- return Futures.transform(session().executeAsync(deleteQuery(objects)), NOOP);
700+ return submitVoidQueryAsync(deleteQueryAsync(objects));
610701 }
611702
612703 /**
704+ * Creates a query to fetch entity given its PRIMARY KEY.
705+ * <p/>
706+ * <p/>
707+ * /**
613708 * Maps the rows from a {@code ResultSet} into the class this is a mapper of.
614709 * <p/>
615710 * 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+}