Skip to content

Conversation

Marcono1234
Copy link
Contributor

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.

Otherwise when a user-defined type adapter with non-final fields (even though it is stateless) is being used as delegate a thread might see an incomplete constructed instance. See Safe Publication and Safe Initialization in Java; the current case of TreeTypeAdapter.delegate() would be similar to the "Unsafe Local DCL & Unsafe Singleton" case shown in that blog post.

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`.
@google-cla google-cla bot added the cla: yes label Sep 24, 2021
@eamonnmcmanus eamonnmcmanus merged commit a92bbf8 into google:master Nov 1, 2021
@Marcono1234 Marcono1234 deleted the marcono1234/TreeTypeAdapter-thread-safety branch November 1, 2021 22:21
tibor-universe pushed a commit to getuniverse/gson that referenced this pull request Nov 21, 2021
* 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants