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

[PIE-2003] Make SyncState variables thread-safe #95

Merged
Merged
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 @@ -25,6 +25,7 @@
import org.hyperledger.besu.util.Subscribers;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;

import com.google.common.annotations.VisibleForTesting;

Expand All @@ -33,12 +34,12 @@ public class SyncState {
private final Blockchain blockchain;
private final EthPeers ethPeers;

private long startingBlock;
private boolean lastInSync = true;
private final Subscribers<InSyncListener> inSyncListeners = Subscribers.create();
private final Subscribers<SyncStatusListener> syncStatusListeners = Subscribers.create();
private Optional<SyncTarget> syncTarget = Optional.empty();
private long chainHeightListenerId;
private volatile long chainHeightListenerId;
private volatile Optional<SyncTarget> syncTarget = Optional.empty();
private volatile long startingBlock;
private final AtomicBoolean lastInSync = new AtomicBoolean(true);

public SyncState(final Blockchain blockchain, final EthPeers ethPeers) {
this.blockchain = blockchain;
Expand Down Expand Up @@ -139,7 +140,7 @@ public void clearSyncTarget() {
replaceSyncTarget(Optional.empty());
}

private void replaceSyncTarget(final Optional<SyncTarget> newTarget) {
private synchronized void replaceSyncTarget(final Optional<SyncTarget> newTarget) {
syncTarget.ifPresent(this::removeEstimatedHeightListener);
syncTarget = newTarget;
newTarget.ifPresent(this::addEstimatedHeightListener);
Expand All @@ -166,8 +167,7 @@ public long bestChainHeight(final long localChainHeight) {

private synchronized void checkInSync() {
final boolean currentInSync = isInSync();
if (lastInSync != currentInSync) {
lastInSync = currentInSync;
if (lastInSync.compareAndSet(!currentInSync, currentInSync)) {
if (!currentInSync) {
// when we fall out of sync change our starting block
startingBlock = blockchain.getChainHeadBlockNumber();
Expand Down