Skip to content

Commit

Permalink
[PIE-2003] Make SyncState variables thread-safe (#95)
Browse files Browse the repository at this point in the history
Signed-off-by: Meredith Baxter <meredith.baxter@consensys.net>
  • Loading branch information
mbaxter authored Oct 8, 2019
1 parent 2626687 commit 13ae431
Showing 1 changed file with 7 additions and 7 deletions.
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

0 comments on commit 13ae431

Please sign in to comment.