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

Safely handle race condition between isEmpty() and lastKey() being called #8362

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.TreeMap;
Expand Down Expand Up @@ -96,7 +97,15 @@ public OptionalLong maybeNextNonce() {
if (pendingTransactions.isEmpty()) {
return OptionalLong.empty();
} else {
return nextGap.isEmpty() ? OptionalLong.of(pendingTransactions.lastKey() + 1) : nextGap;
try {
return nextGap.isEmpty() ? OptionalLong.of(pendingTransactions.lastKey() + 1) : nextGap;
} catch (NoSuchElementException nse) {
// There is a timing condition where isEmpty() returns false, then another thread removes
// the last key before our call to lastKey(). There's no benefit to us adding a mutex to
// prevent the other thread updating the map so we just catch the exception and treat the
// map as empty.
return OptionalLong.empty();
}
}
}

Expand Down
Loading