Skip to content

Commit

Permalink
Improve TreeTypeAdapter thread-safety (google#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 authored and tibor-universe committed Nov 17, 2021
1 parent 08bee30 commit 364ea6d
Showing 1 changed file with 2 additions and 1 deletion.
Original file line number Diff line number Diff line change
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 364ea6d

Please sign in to comment.