Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve TreeTypeAdapter thread-safety #1976

Conversation

Marcono1234
Copy link
Collaborator

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