Elffuss BraidHub

kikocis/java-driver public

JAVA-848: Ability to store a default, shareable CodecRegistry instance.
Changeset0a0b3e93e2c071bef0784692b69d910486fe012d9ea56eec90ed91cf68a5ea7d
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-07-28 18:43 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-08-17 11:08 +02:00
Parentsa00445aecc8c

Browse the files at this changeset

13 files changed

modified changelog/README.md +2 −0
@@ -3,6 +3,8 @@
33 ### 2.2.0-rc3 (in progress)
44
55 - [bug] Propagate CodecRegistry to nested UDTs (JAVA-847)
6+- [improvement] Ability to store a default, shareable CodecRegistry
7+ instance (JAVA-848)
68
79
810 ### 2.2.0-rc2
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +1 −1
@@ -79,7 +79,7 @@
7979
8080 // if this is an internal call, it doesn't matter which codecRegistry will be used
8181 CodecRegistry codecRegistry = session == null ?
82- CodecRegistry.IMMUTABLE_INSTANCE :
82+ CodecRegistry.DEFAULT_INSTANCE :
8383 session.getCluster().getConfiguration().getCodecRegistry();
8484 columnDefs.setCodecRegistry(codecRegistry);
8585
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +6 −1
@@ -925,8 +925,13 @@
925925 /**
926926 * Configures the {@link CodecRegistry} instance to use for the new cluster.
927927 * <p>
928- * If no codec registry is set through this method, a newly-created instance
928+ * If no codec registry is set through this method, {@link CodecRegistry#DEFAULT_INSTANCE}
929929 * will be used instead.
930+ * <p>Note that if two or more {@link Cluster} instances are configured to
931+ * use the default codec registry, they are going to share the same instance.
932+ * In this case, care should be taken when registering new codecs on it as any
933+ * codec registered by one cluster would be immediately available to others
934+ * sharing the same default instance.
930935 *
931936 * @param codecRegistry the codec registry to use.
932937 * @return this Builder.
modified driver-core/src/main/java/com/datastax/driver/core/CodecRegistry.java +141 −155
@@ -22,10 +22,7 @@
2222 import java.util.concurrent.ExecutionException;
2323
2424 import com.google.common.base.Objects;
25-import com.google.common.cache.CacheBuilder;
26-import com.google.common.cache.CacheLoader;
27-import com.google.common.cache.LoadingCache;
28-import com.google.common.collect.ImmutableList;
25+import com.google.common.cache.*;
2926 import com.google.common.collect.ImmutableSet;
3027 import com.google.common.reflect.TypeToken;
3128 import com.google.common.util.concurrent.UncheckedExecutionException;
@@ -48,18 +45,24 @@
4845 * <h3>Usage</h3>
4946 *
5047 * <p>
51- * To create a default {@link CodecRegistry} instance with all the default codecs used
52- * by the Java driver, simply use the following:
48+ * Most users won't need to manipulate {@link CodecRegistry} instances directly.
49+ * Only those willing to register user-defined codecs are required to do so.
50+ * By default, the driver uses {@link CodecRegistry#DEFAULT_INSTANCE}, a shareable
51+ * instance that initially contains all the built-in codecs required by the driver.
5352 *
54- * <pre>
55- * CodecRegistry myCodecRegistry = new CodecRegistry();
56- * </pre>
57- *
58- * Custom {@link TypeCodec}s can be added to a {@link CodecRegistry} via the {@code register} methods:
53+ * <p>
54+ * Users willing to customize their {@link CodecRegistry} can do so by {@code register registering}
55+ * new {@link TypeCodec}s either on {@link CodecRegistry#DEFAULT_INSTANCE},
56+ * or on a newly-crated one:
5957 *
6058 * <pre>
61- * CodecRegistry myCodecRegistry = new CodecRegistry()
62- * .register(myCodec1, myCodec2, myCodec3)
59+ * CodecRegistry myCodecRegistry;
60+ * // use the default instance
61+ * myCodecRegistry = CodecRegistry.DEFAULT_INSTANCE;
62+ * // or alternatively, create a new one
63+ * myCodecRegistry = new CodecRegistry();
64+ * // then
65+ * myCodecRegistry.register(myCodec1, myCodec2, myCodec3);
6366 * </pre>
6467 *
6568 * <p>
@@ -70,6 +73,7 @@
7073 * In order words, it is not possible to replace an existing codec,
7174 * specially the built-in ones; it is only possible to enrich the initial
7275 * set of codecs with new ones.
76+ *
7377 * <p>
7478 * To be used by the driver, {@link CodecRegistry} instances must then
7579 * be associated with a {@link Cluster} instance:
@@ -87,8 +91,7 @@
8791 * </pre>
8892 *
8993 * <p>
90- * For most users, a default {@link CodecRegistry} instance, containing
91- * all the default codecs, should be adequate.
94+ * By default, {@link Cluster} instances will use {@link CodecRegistry#DEFAULT_INSTANCE}.
9295 *
9396 * <h3>Example</h3>
9497 *
@@ -164,41 +167,20 @@
164167 );
165168
166169 /**
167- * The default set of codecs used by the Java driver.
168- * They contain codecs to handle native types, and collections thereof (lists, sets and maps).
169- *
170- * Note that the default set of codecs has no support for
171- * <a href="https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/db/marshal/AbstractType.java">Cassandra custom types</a>;
172- * to be able to deserialize values of such types, you need to manually register an appropriate codec.
173- */
174- static final ImmutableList<TypeCodec<?>> DEFAULT_CODECS;
175-
176- static {
177- ImmutableList.Builder<TypeCodec<?>> builder = new ImmutableList.Builder<TypeCodec<?>>();
178- builder.addAll(PRIMITIVE_CODECS);
179- for (TypeCodec<?> primitiveCodec1 : PRIMITIVE_CODECS) {
180- builder.add(new ListCodec(primitiveCodec1));
181- builder.add(new SetCodec(primitiveCodec1));
182- for (TypeCodec<?> primitiveCodec2 : PRIMITIVE_CODECS) {
183- builder.add(new MapCodec(primitiveCodec1, primitiveCodec2));
184- }
185- }
186- DEFAULT_CODECS = builder.build();
187- }
188-
189- /**
190- * An immutable instance of CodecRegistry.
191- * This is only meant to be used internally by the driver.
170+ * A default instance of CodecRegistry.
171+ * For most applications, sharing a single instance of CodecRegistry is fine.
172+ * But note that any codec registered with this instance will immediately
173+ * be available for all its clients.
192174 */
193- public static final CodecRegistry IMMUTABLE_INSTANCE = new CodecRegistry(true);
175+ public static final CodecRegistry DEFAULT_INSTANCE = new CodecRegistry();
194176
195177 private static final class CacheKey {
196178
197- private final TypeToken<?> javaType;
198-
199179 private final DataType cqlType;
200180
201- public CacheKey(TypeToken<?> javaType, DataType cqlType) {
181+ private final TypeToken<?> javaType;
182+
183+ public CacheKey(DataType cqlType, TypeToken<?> javaType) {
202184 this.javaType = javaType;
203185 this.cqlType = cqlType;
204186 }
@@ -210,7 +192,7 @@
210192 if (o == null || getClass() != o.getClass())
211193 return false;
212194 CacheKey cacheKey = (CacheKey)o;
213- return Objects.equal(javaType, cacheKey.javaType) && Objects.equal(cqlType, cacheKey.cqlType);
195+ return Objects.equal(cqlType, cacheKey.cqlType) && Objects.equal(javaType, cacheKey.javaType);
214196 }
215197
216198 @Override
@@ -219,7 +201,65 @@
219201 }
220202 }
221203
222- private final boolean immutable;
204+ /**
205+ * A complexity-based weigher.
206+ * Weights are computed mainly according to the CQL type:
207+ * <ol>
208+ * <li>Manually-registered codecs always weigh 0;
209+ * <li>Codecs for primtive types weigh 0;
210+ * <li>Codecs for collections weigh the total weight of their inner types + the weight of their level of deepness;
211+ * <li>Codecs for UDTs and tuples weigh the total weight of their inner types + the weight of their level of deepness, but cannot weigh less than 1;
212+ * <li>Codecs for custom (non-CQL) types weigh 1.
213+ * </ol>
214+ * A consequence of this algorithm is that codecs for primitive types and codecs for all "shallow" collections thereof
215+ * are never evicted.
216+ */
217+ private class TypeCodecWeigher implements Weigher<CacheKey, TypeCodec<?>> {
218+
219+ @Override
220+ public int weigh(CacheKey key, TypeCodec<?> value) {
221+ return codecs.contains(value) ? 0 : weigh(key.cqlType, 0);
222+ }
223+
224+ private int weigh(DataType cqlType, int level) {
225+ switch (cqlType.getName()) {
226+ case LIST:
227+ case SET:
228+ case MAP: {
229+ int weight = level;
230+ for (DataType eltType : cqlType.getTypeArguments()) {
231+ weight += weigh(eltType, level + 1);
232+ }
233+ return weight;
234+ }
235+ case UDT: {
236+ int weight = level;
237+ for (UserType.Field field : ((UserType)cqlType)) {
238+ weight += weigh(field.getType(), level + 1);
239+ }
240+ return weight == 0 ? 1 : weight;
241+ }
242+ case TUPLE: {
243+ int weight = level;
244+ for (DataType componentType : ((TupleType)cqlType).getComponentTypes()) {
245+ weight += weigh(componentType, level + 1);
246+ }
247+ return weight == 0 ? 1 : weight;
248+ }
249+ case CUSTOM:
250+ return 1;
251+ default:
252+ return 0;
253+ }
254+ }
255+ }
256+
257+ private class TypeCodecRemovalListener implements RemovalListener<CacheKey, TypeCodec<?>> {
258+ @Override
259+ public void onRemoval(RemovalNotification<CacheKey, TypeCodec<?>> notification) {
260+ logger.trace("Evicting codec from cache: {} (cause: {})", notification.getValue(), notification.getCause());
261+ }
262+ }
223263
224264 /**
225265 * The list of all known codecs.
@@ -234,14 +274,21 @@
234274 */
235275 private final LoadingCache<CacheKey, TypeCodec<?>> cache;
236276
277+ /**
278+ * Creates a default CodecRegistry instance with default cache options.
279+ */
237280 public CodecRegistry() {
238- this(false);
239- }
240-
241- private CodecRegistry(boolean immutable) {
242- this.immutable = immutable;
243- this.codecs = new CopyOnWriteArrayList<TypeCodec<?>>(DEFAULT_CODECS);
281+ this.codecs = new CopyOnWriteArrayList<TypeCodec<?>>(PRIMITIVE_CODECS);
244282 this.cache = CacheBuilder.newBuilder()
283+ // 19 primitive codecs + collections thereof = 19*3 + 19*19 = 418 codecs,
284+ // so let's start with roughly 1/4 of that
285+ .initialCapacity(100)
286+ .weigher(new TypeCodecWeigher())
287+ // a cache with all 418 "basic" codecs weighs 399 (19*2 + 19*19),
288+ // so let's cap at roughly 2.5x this size
289+ .maximumWeight(1000)
290+ .concurrencyLevel(Runtime.getRuntime().availableProcessors() * 4)
291+ .removalListener(new TypeCodecRemovalListener())
245292 .build(
246293 new CacheLoader<CacheKey, TypeCodec<?>>() {
247294 public TypeCodec<?> load(CacheKey cacheKey) {
@@ -257,25 +304,7 @@
257304 * @return this CodecRegistry (for method chaining).
258305 */
259306 public CodecRegistry register(TypeCodec<?> codec) {
260- return register(codec, false);
261- }
262-
263- /**
264- * Register the given codec with this registry.
265- *
266- * @param codec The codec to add to the registry.
267- * @param includeDerivedCollectionCodecs If {@code true}, register not only the given codec
268- * but also collection codecs whose element types are handled by the given codec, i.e.:
269- * <ul>
270- * <li>lists of the codec's type;</li>
271- * <li>sets of the codec's type;</li>
272- * <li>maps of a primitive type to the codec's type, or of the codec's type to a primitive
273- * type;</li>
274- * </ul>
275- * @return this CodecRegistry (for method chaining).
276- */
277- public CodecRegistry register(TypeCodec<?> codec, boolean includeDerivedCollectionCodecs) {
278- return register(Collections.singleton(codec), includeDerivedCollectionCodecs);
307+ return register(Collections.singleton(codec));
279308 }
280309
281310 /**
@@ -285,7 +314,7 @@
285314 * @return this Builder (for method chaining).
286315 */
287316 public CodecRegistry register(TypeCodec<?>... codecs) {
288- return register(Arrays.asList(codecs), false);
317+ return register(Arrays.asList(codecs));
289318 }
290319
291320 /**
@@ -295,42 +324,8 @@
295324 * @return this Builder (for method chaining).
296325 */
297326 public CodecRegistry register(Iterable<? extends TypeCodec<?>> codecs) {
298- return register(codecs, false);
299- }
300-
301- /**
302- * Register the given codecs with this registry.
303- *
304- * @param codecs The codecs to add to the registry.
305- * @param includeDerivedCollectionCodecs If {@code true}, register not only the given codecs
306- * but also collection codecs whose element types are handled by the given codecs, i.e. for
307- * each codec:
308- * <ul>
309- * <li>lists of the codec's type;</li>
310- * <li>sets of the codec's type;</li>
311- * <li>maps of a primitive type to the codec's type, or of the codec's type to a primitive
312- * type;</li>
313- * </ul>
314- * @return this Builder (for method chaining).
315- */
316- public CodecRegistry register(Iterable<? extends TypeCodec<?>> codecs, boolean includeDerivedCollectionCodecs) {
317- if(immutable)
318- throw new UnsupportedOperationException("This CodecRegistry instance is immutable");
319327 for (TypeCodec<?> codec : codecs) {
320- // add this codec to the beginning of the list so that it gets higher priority
321328 this.codecs.add(codec);
322- if(includeDerivedCollectionCodecs){
323- // list and set codecs of the given type
324- this.codecs.add(new ListCodec(codec));
325- this.codecs.add(new SetCodec(codec));
326- // a map which keys and values are of the same given type
327- this.codecs.add(new MapCodec(codec, codec));
328- // map codecs for combinations of the given type with all primitive types
329- for (TypeCodec<?> primitiveCodec : PRIMITIVE_CODECS) {
330- this.codecs.add(new MapCodec(primitiveCodec, codec));
331- this.codecs.add(new MapCodec(codec, primitiveCodec));
332- }
333- }
334329 }
335330 return this;
336331 }
@@ -353,7 +348,7 @@
353348 * <p>
354349 * Regular application code should avoid using this method.
355350 * <p>
356- * Codecs returned by this method are NOT cached.
351+ * Codecs returned by this method are <em>NOT</em> cached.
357352 *
358353 * @param value The value the codec should accept; must not be {@code null}.
359354 * @return A suitable codec.
@@ -381,7 +376,7 @@
381376 * @throws CodecNotFoundException if a suitable codec cannot be found.
382377 */
383378 public <T> TypeCodec<T> codecFor(DataType cqlType) throws CodecNotFoundException {
384- return lookupCache(cqlType, null);
379+ return lookupCodec(cqlType, null);
385380 }
386381
387382 /**
@@ -428,7 +423,7 @@
428423 public <T> TypeCodec<T> codecFor(DataType cqlType, TypeToken<T> javaType) throws CodecNotFoundException {
429424 checkNotNull(cqlType, "Parameter cqlType cannot be null");
430425 checkNotNull(javaType, "Parameter javaType cannot be null");
431- return lookupCache(cqlType, javaType);
426+ return lookupCodec(cqlType, javaType);
432427 }
433428
434429 /**
@@ -441,7 +436,7 @@
441436 * can be an expensive operation; besides, the resulting codec cannot be cached.
442437 * Therefore there might be a performance penalty when using this method.
443438 * <p>
444- * Codecs returned by this method <em>may</em> be cached.
439+ * Codecs returned by this method are <em>NOT</em> cached.
445440 *
446441 * @param cqlType The {@link DataType CQL type} the codec should accept; must not be {@code null}.
447442 * @param value The value the codec should accept; must not be {@code null}.
@@ -454,16 +449,18 @@
454449 return findCodec(cqlType, value);
455450 }
456451
457- private <T> TypeCodec<T> lookupCache(DataType cqlType, TypeToken<T> javaType) {
452+ private <T> TypeCodec<T> lookupCodec(DataType cqlType, TypeToken<T> javaType) {
458453 checkNotNull(cqlType, "Parameter cqlType cannot be null");
459- if(logger.isTraceEnabled())
460- logger.trace("Looking up codec for {} <-> {}", cqlType, javaType);
461- CacheKey cacheKey = new CacheKey(javaType, cqlType);
454+ logger.trace("Querying cache for codec [{} <-> {}]", cqlType, javaType);
455+ CacheKey cacheKey = new CacheKey(cqlType, javaType);
462456 try {
463- return (TypeCodec<T>)cache.get(cacheKey);
457+ TypeCodec<?> codec = cache.get(cacheKey);
458+ logger.trace("Returning cached codec [{} <-> {}]", cqlType, javaType);
459+ return (TypeCodec<T>)codec;
464460 } catch (UncheckedExecutionException e) {
465- if(e.getCause() instanceof CodecNotFoundException)
466- throw (CodecNotFoundException)e.getCause();
461+ if(e.getCause() instanceof CodecNotFoundException) {
462+ throw (CodecNotFoundException) e.getCause();
463+ }
467464 throw new CodecNotFoundException(e.getCause(), cqlType, javaType);
468465 } catch (ExecutionException e) {
469466 throw new CodecNotFoundException(e.getCause(), cqlType, javaType);
@@ -472,62 +469,53 @@
472469
473470 private <T> TypeCodec<T> findCodec(DataType cqlType, TypeToken<T> javaType) {
474471 checkNotNull(cqlType, "Parameter cqlType cannot be null");
475- if(logger.isTraceEnabled())
476- logger.trace("Looking for codec [{} <-> {}]", cqlType == null ? "ANY" : cqlType, javaType == null ? "ANY" : javaType);
472+ logger.trace("Looking for codec [{} <-> {}]",
473+ cqlType == null ? "ANY" : cqlType,
474+ javaType == null ? "ANY" : javaType);
477475 for (TypeCodec<?> codec : codecs) {
478476 if ((cqlType == null || codec.accepts(cqlType)) && (javaType == null || codec.accepts(javaType))) {
479- if(logger.isTraceEnabled())
480- logger.trace("Codec found: {}", codec);
477+ logger.trace("Codec found: {}", codec);
481478 return (TypeCodec<T>)codec;
482479 }
483480 }
484- // codec not found among the reservoir of known codecs, try to create an ad-hoc codec;
485- // this situation should happen mainly when dealing with enums, tuples and UDTs,
486- // and collections thereof.
487- TypeCodec<T> codec = maybeCreateCodec(cqlType, javaType);
488- if (codec == null)
489- throw logErrorAndThrow(cqlType, javaType);
490- // double-check that the created codec satisfies the initial request
491- if (!codec.accepts(cqlType) || (javaType != null && !codec.accepts(javaType)))
492- throw logErrorAndThrow(cqlType, javaType);
493-
494- if(logger.isTraceEnabled())
495- logger.trace("Codec found: {}", codec);
496- // add the codec for future use
497- codecs.addIfAbsent(codec);
498- return codec;
481+ return createCodec(cqlType, javaType);
499482 }
500483
501484 private <T> TypeCodec<T> findCodec(DataType cqlType, T value) {
502485 checkNotNull(value, "Parameter value cannot be null");
503- if(logger.isTraceEnabled())
504- logger.trace("Looking for codec [{} <-> {}]", cqlType == null ? "ANY" : cqlType, value.getClass());
486+ logger.trace("Looking for codec [{} <-> {}]", cqlType == null ? "ANY" : cqlType, value.getClass());
505487 for (TypeCodec<?> codec : codecs) {
506488 if ((cqlType == null || codec.accepts(cqlType)) && codec.accepts(value)) {
507- if(logger.isTraceEnabled())
508- logger.trace("Codec found: {}", codec);
489+ logger.trace("Codec found: {}", codec);
509490 return (TypeCodec<T>)codec;
510491 }
511492 }
512- // codec not found among the reservoir of known codecs, try to create an ad-hoc codec;
513- // this situation should happen mainly when dealing with enums, tuples and UDTs,
514- // and collections thereof.
493+ return createCodec(cqlType, value);
494+ }
495+
496+ private <T> TypeCodec<T> createCodec(DataType cqlType, TypeToken<T> javaType) {
497+ TypeCodec<T> codec = maybeCreateCodec(cqlType, javaType);
498+ if (codec == null)
499+ throw newException(cqlType, javaType);
500+ // double-check that the created codec satisfies the initial request
501+ if (!codec.accepts(cqlType) || (javaType != null && !codec.accepts(javaType)))
502+ throw newException(cqlType, javaType);
503+ logger.trace("Codec created: {}", codec);
504+ return codec;
505+ }
506+
507+ private <T> TypeCodec<T> createCodec(DataType cqlType, T value) {
515508 TypeCodec<T> codec = maybeCreateCodec(cqlType, value);
516509 if(codec == null)
517- throw logErrorAndThrow(cqlType, TypeToken.of(value.getClass()));
510+ throw newException(cqlType, TypeToken.of(value.getClass()));
518511 // double-check that the created codec satisfies the initial request
519512 if((cqlType != null && !codec.accepts(cqlType)) || !codec.accepts(value))
520- throw logErrorAndThrow(cqlType, TypeToken.of(value.getClass()));
521- if(logger.isTraceEnabled())
522- logger.trace("Codec found: {}", codec);
523- // add the codec for future use
524- codecs.addIfAbsent(codec);
513+ throw newException(cqlType, TypeToken.of(value.getClass()));
514+ logger.trace("Codec created: {}", codec);
525515 return codec;
526516 }
527517
528518 private <T> TypeCodec<T> maybeCreateCodec(DataType cqlType, TypeToken<T> javaType) {
529- if(immutable)
530- return null;
531519 checkNotNull(cqlType);
532520
533521 if ((cqlType.getName() == VARCHAR || cqlType.getName() == TEXT) && javaType != null && Enum.class.isAssignableFrom(javaType.getRawType())) {
@@ -579,9 +567,8 @@
579567 }
580568
581569 private <T> TypeCodec<T> maybeCreateCodec(DataType cqlType, T value) {
582- if(immutable)
583- return null;
584570 checkNotNull(value);
571+
585572 if ((cqlType == null || cqlType.getName() == VARCHAR || cqlType.getName() == TEXT) && value instanceof Enum) {
586573 return new EnumStringCodec(value.getClass());
587574 }
@@ -653,11 +640,10 @@
653640 return null;
654641 }
655642
656- private static CodecNotFoundException logErrorAndThrow(DataType cqlType, TypeToken<?> javaType) {
643+ private static CodecNotFoundException newException(DataType cqlType, TypeToken<?> javaType) {
657644 String msg = String.format("Codec not found for requested operation: [%s <-> %s]",
658645 cqlType == null ? "ANY" : cqlType,
659646 javaType == null ? "ANY" : javaType);
660- logger.error(msg);
661647 return new CodecNotFoundException(msg, cqlType, javaType);
662648 }
663649
modified driver-core/src/main/java/com/datastax/driver/core/Configuration.java +7 −1
@@ -142,6 +142,12 @@
142142
143143 /**
144144 * Returns the {@link CodecRegistry} instance for this configuration.
145+ * <p>
146+ * Note that this method could return {@link CodecRegistry#DEFAULT_INSTANCE}
147+ * if no specific codec registry has been set on the {@link Cluster}.
148+ * In this case, care should be taken when registering new codecs as they would be
149+ * immediately available to other {@link Cluster} instances sharing the same default instance.
150+ *
145151 * @return the {@link CodecRegistry} instance for this configuration.
146152 */
147153 public CodecRegistry getCodecRegistry() {
@@ -257,7 +263,7 @@
257263 metricsOptions != null ? metricsOptions : new MetricsOptions(),
258264 queryOptions != null ? queryOptions : new QueryOptions(),
259265 nettyOptions != null ? nettyOptions : NettyOptions.DEFAULT_INSTANCE,
260- codecRegistry != null ? codecRegistry : new CodecRegistry());
266+ codecRegistry != null ? codecRegistry : CodecRegistry.DEFAULT_INSTANCE);
261267 }
262268 }
263269 }
modified driver-core/src/main/java/com/datastax/driver/core/GettableByIndexData.java +6 −3
@@ -405,9 +405,12 @@
405405 /**
406406 * Returns the {@code i}th value as the Java type matching its CQL type.
407407 * <p>
408- * This method is not suitable to use with custom codecs: it will always
409- * use the default ones for the underlying CQL type. If you want to use
410- * non-default codecs, use {@link #get(int, Class)} or {@link #get(int, TypeToken)} instead.
408+ * This method uses the default codec for the underlying CQL type
409+ * to perform deserialization, and is safe to be used
410+ * <em>as long as only default codecs are in use</em>.
411+ * If a second, custom codec for the same CQL type is registered, which one will
412+ * be used is unspecified; in such cases, it is preferable to use
413+ * the more deterministic methods {@link #get(int, Class)} or {@link #get(int, TypeToken)} instead.
411414 *
412415 * @param i the index to retrieve.
413416 * @return the value of the {@code i}th value as the Java type matching its CQL type.
modified driver-core/src/main/java/com/datastax/driver/core/GettableByNameData.java +6 −3
@@ -404,9 +404,12 @@
404404 /**
405405 * Returns the value for {@code name} as the Java type matching its CQL type.
406406 * <p>
407- * This method is not suitable to use with custom codecs: it will always
408- * use the default ones for the underlying CQL type. If you want to use
409- * non-default codecs, use {@link #get(String, Class)} or {@link #get(String, TypeToken)} instead.
407+ * This method uses the default codec for the underlying CQL type
408+ * to perform deserialization, and is safe to be used
409+ * <em>as long as only default codecs are in use</em>.
410+ * If a second, custom codec for the same CQL type is registered, which one will
411+ * be used is unspecified; in such cases, it is preferable to use
412+ * the more deterministic methods {@link #get(String, Class)} or {@link #get(String, TypeToken)} instead.
410413 *
411414 * @param name the name to retrieve.
412415 * @return the value of the {@code i}th value as the Java type matching its CQL type.
modified driver-core/src/main/java/com/datastax/driver/core/Responses.java +1 −1
@@ -389,7 +389,7 @@
389389 String name = CBUtil.readString(body);
390390 // will set the appropriate CodecRegistry instance later
391391 // when the message will be decoded into either a PreparedStatement or a ResultSet
392- DataType type = DataType.decode(body, protocolVersion, null);
392+ DataType type = DataType.decode(body, protocolVersion, CodecRegistry.DEFAULT_INSTANCE);
393393 defs[i] = new ColumnDefinitions.Definition(ksName, cfName, name, type);
394394 }
395395
modified driver-core/src/main/java/com/datastax/driver/core/SettableByIndexData.java +38 −13
@@ -252,10 +252,14 @@
252252 * <p>
253253 * Note about performance: this method must perform a runtime inspection of the provided list,
254254 * in order to guess the best codec to serialize the list elements.
255- * The result of such inspection cannot be cached and thus must be performed for each invocation
256- * of this method, which may incur in a performance penalty.
257- * To circumvent this problem, consider using {@link #setList(int, List, Class)} or
258- * {@link #setList(int, List, TypeToken)}, which do not suffer from such symptoms.
255+ * <p>
256+ * Furthermore, if two or more codecs are available
257+ * for the underlying CQL type ({@code list}), <em>which one will be used will depend
258+ * on the actual object being serialized</em>.
259+ * <p>
260+ * For these reasons, it is generally preferable to use the more
261+ * deterministic methods {@link #setList(int, List, Class)} or
262+ * {@link #setList(int, List, TypeToken)}.
259263 *
260264 * @param i the index of the value to set.
261265 * @param v the value to set.
@@ -327,8 +331,14 @@
327331 * in order to guess the best codec to serialize the map entries.
328332 * The result of such inspection cannot be cached and thus must be performed for each invocation
329333 * of this method, which may incur in a performance penalty.
330- * To circumvent this problem, consider using {@link #setMap(int, Map, Class, Class)} or
331- * {@link #setMap(int, Map, TypeToken, TypeToken)}, which do not suffer from such symptoms.
334+ * <p>
335+ * Furthermore, if two or more codecs are available
336+ * for the underlying CQL type ({@code map}), <em>which one will be used will depend
337+ * on the actual object being serialized</em>.
338+ * <p>
339+ * For these reasons, it is generally preferable to use the more
340+ * deterministic methods {@link #setMap(int, Map, Class, Class)} or
341+ * {@link #setMap(int, Map, TypeToken, TypeToken)}.
332342 *
333343 * @param i the index of the value to set.
334344 * @param v the value to set.
@@ -398,12 +408,18 @@
398408 * <p>
399409 * Please note that {@code null} values are not supported inside collection by CQL.
400410 * <p>
401- * Note about performance: this method must perform a runtime inspection of the provided map,
402- * in order to guess the best codec to serialize the map entries.
411+ * Note about performance: this method must perform a runtime inspection of the provided set,
412+ * in order to guess the best codec to serialize the set elements.
403413 * The result of such inspection cannot be cached and thus must be performed for each invocation
404414 * of this method, which may incur in a performance penalty.
405- * To circumvent this problem, consider using {@link #setSet(int, Set, Class)} or
406- * {@link #setSet(int, Set, TypeToken)}, which do not suffer from such symptoms.
415+ * <p>
416+ * Furthermore, if two or more codecs are available
417+ * for the underlying CQL type ({@code set}), <em>which one will be used will depend
418+ * on the actual object being serialized</em>.
419+ * <p>
420+ * For these reasons, it is generally preferable to use the more
421+ * deterministic methods {@link #setSet(int, Set, Class)} or
422+ * {@link #setSet(int, Set, TypeToken)}.
407423 *
408424 * @param i the index of the value to set.
409425 * @param v the value to set.
@@ -506,9 +522,18 @@
506522 /**
507523 * Sets the {@code i}th value to the provided value.
508524 * <p>
509- * This method is not suitable to use with custom codecs: it will always
510- * use the default ones for the underlying CQL type. If you want to use
511- * non-default codecs, use {@link #set(int, V, Class)} or {@link #set(int, V, TypeToken)} instead.
525+ * Note about performance: this method must perform a runtime inspection of the provided object,
526+ * in order to guess the best codec to serialize it.
527+ * The result of such inspection cannot be cached and thus must be performed for each invocation
528+ * of this method, which may incur in a performance penalty.
529+ * <p>
530+ * Furthermore, if two or more codecs are available
531+ * for the underlying CQL type, <em>which one will be used will depend
532+ * on the actual object being serialized</em>.
533+ * <p>
534+ * For these reasons, it is generally preferable to use the more
535+ * deterministic methods {@link #set(int, V, Class)}
536+ * or {@link #set(int, V, TypeToken)} instead.
512537 *
513538 * @param i the index of the value to set.
514539 * @param v the value to set; may be {@code null}.
modified driver-core/src/main/java/com/datastax/driver/core/SettableByNameData.java +36 −10
@@ -298,8 +298,14 @@
298298 * in order to guess the best codec to serialize the list elements.
299299 * The result of such inspection cannot be cached and thus must be performed for each invocation
300300 * of this method, which may incur in a performance penalty.
301- * To circumvent this problem, consider using {@link #setList(String, List, Class)} or
302- * {@link #setList(String, List, TypeToken)}, which do not suffer from such symptoms.
301+ * <p>
302+ * Furthermore, if two or more codecs are available
303+ * for the underlying CQL type ({@code list}), <em>which one will be used will depend
304+ * on the actual object being serialized</em>.
305+ * <p>
306+ * For these reasons, it is generally preferable to use the more
307+ * deterministic methods {@link #setList(String, List, Class)} or
308+ * {@link #setList(String, List, TypeToken)}.
303309 *
304310 * @param name the name of the value to set; if {@code name} is present multiple
305311 * times, all its values are set.
@@ -373,8 +379,14 @@
373379 * in order to guess the best codec to serialize the map entries.
374380 * The result of such inspection cannot be cached and thus must be performed for each invocation
375381 * of this method, which may incur in a performance penalty.
376- * To circumvent this problem, consider using {@link #setMap(String, Map, Class, Class)} or
377- * {@link #setMap(String, Map, TypeToken, TypeToken)}, which do not suffer from such symptoms.
382+ * <p>
383+ * Furthermore, if two or more codecs are available
384+ * for the underlying CQL type ({@code map}), <em>which one will be used will depend
385+ * on the actual object being serialized</em>.
386+ * <p>
387+ * For these reasons, it is generally preferable to use the more
388+ * deterministic methods {@link #setMap(String, Map, Class, Class)} or
389+ * {@link #setMap(String, Map, TypeToken, TypeToken)}.
378390 *
379391 * @param name the name of the value to set; if {@code name} is present multiple
380392 * times, all its values are set.
@@ -449,11 +461,17 @@
449461 * Please note that {@code null} values are not supported inside collection by CQL.
450462 * <p>
451463 * Note about performance: this method must perform a runtime inspection of the provided map,
452- * in order to guess the best codec to serialize the map entries.
464+ * in order to guess the best codec to serialize the set elements.
453465 * The result of such inspection cannot be cached and thus must be performed for each invocation
454466 * of this method, which may incur in a performance penalty.
455- * To circumvent this problem, consider using {@link #setSet(String, Set, Class)} or
456- * {@link #setSet(String, Set, TypeToken)}, which do not suffer from such symptoms.
467+ * <p>
468+ * Furthermore, if two or more codecs are available
469+ * for the underlying CQL type ({@code set}), <em>which one will be used will depend
470+ * on the actual object being serialized</em>.
471+ * <p>
472+ * For these reasons, it is generally preferable to use the more
473+ * deterministic methods {@link #setSet(String, Set, Class)} or
474+ * {@link #setSet(String, Set, TypeToken)}.
457475 *
458476 * @param name the name of the value to set; if {@code name} is present multiple
459477 * times, all its values are set.
@@ -566,9 +584,17 @@
566584 /**
567585 * Sets the value for (all occurrences of) variable {@code name} to the provided value.
568586 * <p>
569- * This method is not suitable to use with custom codecs: it will always
570- * use the default ones for the underlying CQL type. If you want to use
571- * non-default codecs, use {@link #set(String, V, Class)} or {@link #set(String, V, TypeToken)} instead.
587+ * Note about performance: this method must perform a runtime inspection of the provided object,
588+ * in order to guess the best codec to serialize it.
589+ * The result of such inspection cannot be cached and thus must be performed for each invocation
590+ * of this method, which may incur in a performance penalty.
591+ * <p>
592+ * Furthermore, if two or more codecs are available
593+ * for the underlying CQL type, <em>which one will be used will depend
594+ * on the actual object being serialized</em>.
595+ * <p>
596+ * For these reasons, it is generally preferable to use the more
597+ * deterministic methods {@link #set(String, V, Class)} or {@link #set(String, V, TypeToken)} instead.
572598 *
573599 * @param name the name of the value to set; if {@code name} is present multiple
574600 * times, all its values are set.
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +4 −4
@@ -55,7 +55,7 @@
5555 * <ol>
5656 * <li>{@link #serialize(Object,ProtocolVersion)}: used to serialize from the codec's Java type to a
5757 * {@link ByteBuffer} instance corresponding to the codec's CQL type;</li>
58- * <li>{@link #deserialize(ByteBuffer,ProtocolVersion)}}: used to deserialize a {@link ByteBuffer} instance
58+ * <li>{@link #deserialize(ByteBuffer,ProtocolVersion)}: used to deserialize a {@link ByteBuffer} instance
5959 * corresponding to the codec's CQL type to the codec's Java type.</li>
6060 * </ol>
6161 *
@@ -73,9 +73,9 @@
7373 * Codecs also have the following inspection methods:
7474 *
7575 * <ol>
76- * <li>{@link #accepts(DataType)}}}: returns true if the codec can deserialize the given CQL type;</li>
77- * <li>{@link #accepts(TypeToken)}}: returns true if the codec can serialize the given Java type;</li>
78- * <li>{@link #accepts(Object)}}; returns true if the codec can serialize the given object.</li>
76+ * <li>{@link #accepts(DataType)}: returns true if the codec can deserialize the given CQL type;</li>
77+ * <li>{@link #accepts(TypeToken)}: returns true if the codec can serialize the given Java type;</li>
78+ * <li>{@link #accepts(Object)}; returns true if the codec can serialize the given object.</li>
7979 * </ol>
8080 *
8181 * <h3>Implementation notes</h3>
modified driver-core/src/test/java/com/datastax/driver/core/TypeCodecOverlappingJavaTypeIntegrationTest.java +1 −1
@@ -52,7 +52,7 @@
5252 @Override
5353 protected Cluster.Builder configure(Cluster.Builder builder) {
5454 return builder.withCodecRegistry(
55- new CodecRegistry().register(new IntToStringCodec(), true)
55+ new CodecRegistry().register(new IntToStringCodec())
5656 );
5757 }
5858
modified features/custom_codecs/README.md +16 −8
@@ -108,25 +108,31 @@
108108 to only then parse the String into an object.
109109 More advanced solutions that read the underlying byte stream directly are possible.
110110
111-The second step is to register your codec:
111+The second step is to register your codec with a `CodecRegistry` instance:
112112
113113 ```java
114114 ObjectMapper objectMapper = ...
115115 JsonCodec<MyPojo> myJsonCodec = new JsonCodec<MyPojo>(MyPojo.class, objectMapper);
116-CodecRegistry myCodecRegistry = new CodecRegistry().register(myJsonCodec);
116+CodecRegistry myCodecRegistry = cluster.getConfiguration().getCodecRegistry();
117+myCodecRegistry.register(myJsonCodec);
117118 ```
118119
119-When you instantiate a `CodecRegistry`, it automatically registers all the default codecs used by the driver.
120-This ensures that the registry will not lack of an essential codec. *You cannot deregister default codecs, only
121-register new ones*.
120+As you can see, the easiest way to do so is to access the `Cluster`'s `CodecRegistry`.
121+By default, `Cluster` instances will use `CodecRegistry.DEFAULT_INSTANCE`,
122+which should be adequate for most users.
122123
123-The third step is to associate your `CodecRegistry` instance with your `Cluster` instance:
124+It is however possible to create a `Cluster` using a different `CodecRegistry`:
124125
125126 ```java
127+CodecRegistry myCodecRegistry = new CodecRegistry();
126128 Cluster cluster = new Cluster.builder().withCodecRegistry(myCodecRegistry).build();
127129 ```
128130
129-From now on, your codec is fully operational. It will be used every time the driver encounters
131+Note: when you instantiate a new `CodecRegistry`, it automatically registers all the default codecs used by the driver.
132+This ensures that the new registry will not lack of an essential codec. *You cannot deregister default codecs, only
133+register new ones*.
134+
135+From now on, your custom codec is fully operational. It will be used every time the driver encounters
130136 a `MyPojo` instance when executing queries, or when you ask it to retrieve a `MyPojo` instance from a `ResultSet`.
131137
132138 For example, here is how to save a `MyPojo` object:
@@ -262,9 +268,11 @@
262268
263269 Again, the driver provides a convenient base class: [MappingCodec].
264270
265-Now, create your `CodecRegistry` and `Cluster` instances the usual way:
271+Now (and only if you intend to use your own `CodecRegistry`),
272+create it and register it on your `Cluster` instance:
266273
267274 ```java
275+// only if you do not intend to use CodecRegistry.DEFAULT_INSTANCE
268276 CodecRegistry codecRegistry = new CodecRegistry();
269277 Cluster cluster = Cluster.builder()
270278 .addContactPoints(...)