Skip to content

Commit

Permalink
Improve TreeTypeAdapter thread-safety (#1976)
Browse files Browse the repository at this point in the history
* Improve TreeTypeAdapter thread-safety

Gson claims to be thread-safe so TreeTypeAdapter.delegate() might be
called by multiple threads. To guarantee that each thread sees a fully
constructed `delegate`, the field has to be `volatile`.

* Improve TreeTypeAdapter thread race comment
  • Loading branch information
Marcono1234 committed Nov 1, 2021
1 parent deaa3a6 commit a92bbf8
Showing 1 changed file with 2 additions and 1 deletion.
Expand Up @@ -47,7 +47,7 @@ public final class TreeTypeAdapter<T> extends TypeAdapter<T> {
private final GsonContextImpl context = new GsonContextImpl();

/** The delegate is lazily created because it may not be needed, and creating it may fail. */
private TypeAdapter<T> delegate;
private volatile TypeAdapter<T> delegate;

public TreeTypeAdapter(JsonSerializer<T> serializer, JsonDeserializer<T> deserializer,
Gson gson, TypeToken<T> typeToken, TypeAdapterFactory skipPast) {
Expand Down Expand Up @@ -83,6 +83,7 @@ public TreeTypeAdapter(JsonSerializer<T> serializer, JsonDeserializer<T> deseria
}

private TypeAdapter<T> delegate() {
// A race might lead to `delegate` being assigned by multiple threads but the last assignment will stick
TypeAdapter<T> d = delegate;
return d != null
? d
Expand Down

0 comments on commit a92bbf8

Please sign in to comment.