Peer: WIP/Question: replace ReentrantLock

Replace `pingIntervalsLock.lock()` with `synchronizedLock(pingIntervals)`.

I'm not sure this is equivalent or if we are losing any functionality by doing this.
Note that before the Duration[] was nullable, so there had to be something to lock on.
Now that the Deque is final, we can use it.
This commit is contained in:
Sean Gilligan 2023-03-19 17:08:55 -07:00
parent 466444ebf7
commit db28774996

View file

@ -169,10 +169,9 @@ public class Peer extends PeerSocketHandler {
@GuardedBy("getAddrFutures") private final LinkedList<CompletableFuture<AddressMessage>> getAddrFutures; @GuardedBy("getAddrFutures") private final LinkedList<CompletableFuture<AddressMessage>> getAddrFutures;
// Outstanding pings against this peer and how long the last one took to complete. // Outstanding pings against this peer and how long the last one took to complete.
private final ReentrantLock pingIntervalsLock = new ReentrantLock(); private final Deque<Duration> pingIntervals = new ArrayDeque<>(PING_MOVING_AVERAGE_WINDOW);
@GuardedBy("pingIntervalsLock") private final Deque<Duration> pingIntervals = new ArrayDeque<>(PING_MOVING_AVERAGE_WINDOW); private volatile Duration lastPing = null; // should only be written while holding lock on pingIntervals
private volatile Duration lastPing = null; // should only be written while holding pingIntervalsLock private volatile Duration averagePing = null; // should only be written while holding lock on pingIntervals
private volatile Duration averagePing = null; // should only be written while holding pingIntervalsLock
private final CopyOnWriteArrayList<PendingPing> pendingPings; private final CopyOnWriteArrayList<PendingPing> pendingPings;
// Disconnect from a peer that is not responding to Pings // Disconnect from a peer that is not responding to Pings
@ -1513,8 +1512,7 @@ public class Peer extends PeerSocketHandler {
/** Adds a ping time sample to the averaging window. */ /** Adds a ping time sample to the averaging window. */
private void addPingInterval(Duration sample) { private void addPingInterval(Duration sample) {
pingIntervalsLock.lock(); synchronized (pingIntervals) {
try {
if (pingIntervals.size() >= PING_MOVING_AVERAGE_WINDOW) { if (pingIntervals.size() >= PING_MOVING_AVERAGE_WINDOW) {
// Remove oldest sample from front of queue // Remove oldest sample from front of queue
pingIntervals.remove(); pingIntervals.remove();
@ -1527,8 +1525,6 @@ public class Peer extends PeerSocketHandler {
.reduce(Duration::plus) .reduce(Duration::plus)
.map(d -> d.dividedBy(pingIntervals.size())) .map(d -> d.dividedBy(pingIntervals.size()))
.orElse(null); .orElse(null);
} finally {
pingIntervalsLock.unlock();
} }
} }