Created threadsafe implementation of JsonAdapter invocation. Also fixed a bug where runtime generated typeadapters were being carried over from a toJson/fromJson call to the next.

This commit is contained in:
Inderjeet Singh 2014-03-09 23:00:53 +00:00
parent e280ffd7e2
commit 6e8d3cd65e

View File

@ -115,6 +115,15 @@ public final class Gson {
private final Map<TypeToken<?>, TypeAdapter<?>> typeTokenCache
= Collections.synchronizedMap(new HashMap<TypeToken<?>, TypeAdapter<?>>());
/** Indicates whether Gson is in the phase of constructor invocation. It is used to determine
* whether to add a constructor in preconfiguredGeneratedTypeAdapter set or not. */
private boolean inConstructorPhase = true;
/** List of type adapters that are generated by Gson during its constructor */
private Set<TypeAdapter<?>> preconfiguredGeneratedTypeAdapters = new HashSet<TypeAdapter<?>>();
/** List of type adapters that are generated by Gson during toJson/fromJson. */
private final ThreadLocal<Set<TypeAdapter<?>>> runtimeGeneratedTypeAdapters =
new ThreadLocal<Set<TypeAdapter<?>>>();
private final List<TypeAdapterFactory> factories;
private final ConstructorConstructor constructorConstructor;
@ -245,6 +254,8 @@ public final class Gson {
constructorConstructor, fieldNamingPolicy, excluder));
this.factories = Collections.unmodifiableList(factories);
this.preconfiguredGeneratedTypeAdapters = Collections.unmodifiableSet(preconfiguredGeneratedTypeAdapters);
inConstructorPhase = false;
}
private TypeAdapter<Number> doubleAdapter(boolean serializeSpecialFloatingPointValues) {
@ -907,13 +918,25 @@ public final class Gson {
.toString();
}
private final Set<TypeAdapter<?>> generatedTypeAdapters = new HashSet<TypeAdapter<?>>();
public static final class $$Internal {
public static void addGeneratedTypeAdapter(Gson gson, TypeAdapter<?> typeAdapter) {
gson.generatedTypeAdapters.add(typeAdapter);
if (gson.inConstructorPhase) {
gson.preconfiguredGeneratedTypeAdapters.add(typeAdapter);
} else {
Set<TypeAdapter<?>> adapters = getRuntimeGeneratedTypeAdapters(gson);
adapters.add(typeAdapter);
}
}
public static boolean isGeneratedTypeAdapter(Gson gson, TypeAdapter<?> typeAdapter) {
return gson.generatedTypeAdapters.contains(typeAdapter);
boolean generated = gson.preconfiguredGeneratedTypeAdapters.contains(typeAdapter);
if (!generated) generated = getRuntimeGeneratedTypeAdapters(gson).contains(typeAdapter);
return generated;
}
private static Set<TypeAdapter<?>> getRuntimeGeneratedTypeAdapters(Gson gson) {
Set<TypeAdapter<?>> adapters = gson.runtimeGeneratedTypeAdapters.get();
if (adapters == null) adapters = new HashSet<TypeAdapter<?>>();
gson.runtimeGeneratedTypeAdapters.set(adapters);
return adapters;
}
}
}