Skip to content

Gracefully handle parse failure with locking#4114

Merged
JakeWharton merged 1 commit intotrunkfrom
jw.locks.2024-03-22
Mar 27, 2024
Merged

Gracefully handle parse failure with locking#4114
JakeWharton merged 1 commit intotrunkfrom
jw.locks.2024-03-22

Conversation

@JakeWharton
Copy link
Copy Markdown
Collaborator

Before we would poison the map with the lock object so the second caller would get a weird ClassCastException.

Closes #4113


  • CHANGELOG.md's "Unreleased" section has been updated, if applicable.

Before we would poison the map with the lock object so the second caller would get a weird ClassCastException.
@JakeWharton JakeWharton requested a review from swankjesse March 22, 2024 14:15
Comment on lines +236 to +240
} catch (Throwable e) {
// Remove the lock on failure. Any other locked threads will retry as a result.
serviceMethodCache.remove(method);
throw e;
}
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change is here

Comment on lines +256 to +259
if (result == null) {
// The other thread failed its parsing. We will retry (and probably also fail).
continue;
}
Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And here (plus the enclosing while (true))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am thinking about whether this situation is possible: thread 1 put its lock1to the cache, granted the right to parse the method, but failed and threw an exception. Then, thread 2, which was waiting for thread 1 to parse the method, synchronize lock1 successfully, find the result is null, continue the while loop and put its lock2 to the cache. Then, Thread 3 synchronize lock1. However, the result retrieved from the cache by thread 3 is lock2 instead of null. Thus, thread 3 try to cast object to ServiceMethod and a ClassCastException happens. Can we check result instanceof ServiceMethod<?> here? What's more, can we check lookup instanceof ServiceMethod<?> before synchronize lookup to eliminate the pointless lock and redundant lookup you've metioned in comment(line 253)? Thanks.

@JakeWharton JakeWharton merged commit c579693 into trunk Mar 27, 2024
@JakeWharton JakeWharton deleted the jw.locks.2024-03-22 branch March 27, 2024 18:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Object cannot be cast to class retrofit2.ServiceMethod

3 participants