Improve TreeTypeAdapter thread-safety (#1976)

* 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
This commit is contained in:
Marcono1234 2021-11-01 23:13:08 +01:00 committed by GitHub
parent deaa3a6cd9
commit a92bbf849c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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) {
@ -83,6 +83,7 @@ public final class TreeTypeAdapter<T> extends TypeAdapter<T> {
}
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