Skip to content

Commit

Permalink
Code refactoring in ExecutionBlockRetriever
Browse files Browse the repository at this point in the history
  • Loading branch information
Vovchyk committed Nov 7, 2022
1 parent 8c2f11e commit 45a7a49
Showing 1 changed file with 35 additions and 20 deletions.
55 changes: 35 additions & 20 deletions rskj-core/src/main/java/co/rsk/rpc/ExecutionBlockRetriever.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,26 +68,7 @@ public Result retrieveExecutionBlock(String bnOrId) {
}

if (PENDING_ID.equals(bnOrId)) {
Block bestBlock = blockchain.getBestBlock();
Result result = cachedPendingBlockResult.get();
// optimistic check without the lock
if (result != null && result.getBlock().getParentHash().equals(bestBlock.getHash())) {
return result;
}

synchronized (pendingBlockLock) {
// build a new pending block, but before that just in case check if one hasn't been built while being locked
bestBlock = blockchain.getBestBlock();
result = cachedPendingBlockResult.get();
if (result != null && result.getBlock().getParentHash().equals(bestBlock.getHash())) {
return result;
}

result = Result.ofBlockResult(builder.buildPending(bestBlock.getHeader()));
cachedPendingBlockResult.set(result);

return result;
}
return getPendingBlockResult();
}

// Is the block specifier either a hexadecimal or decimal number?
Expand All @@ -114,6 +95,40 @@ public Result retrieveExecutionBlock(String bnOrId) {
bnOrId));
}

@Nonnull
private Result getPendingBlockResult() {
Block bestBlock = blockchain.getBestBlock();

// optimistic check without the lock
Result result = getCachedResultFor(bestBlock);
if (result != null) {
return result;
}

synchronized (pendingBlockLock) {
// build a new pending block, but before that just in case check if one hasn't been built while being locked
bestBlock = blockchain.getBestBlock();
result = getCachedResultFor(bestBlock);
if (result != null) {
return result;
}

result = Result.ofBlockResult(builder.buildPending(bestBlock.getHeader()));
cachedPendingBlockResult.set(result);

return result;
}
}

@Nullable
private Result getCachedResultFor(@Nonnull Block bestBlock) {
Result result = cachedPendingBlockResult.get();
if (result != null && result.getBlock().getParentHash().equals(bestBlock.getHash())) {
return result;
}
return null;
}

@VisibleForTesting
Result getCachedPendingBlockResult() {
return cachedPendingBlockResult.get();
Expand Down

0 comments on commit 45a7a49

Please sign in to comment.