Skip to content

Commit

Permalink
fix thread race issue when connecting to cormorant electrum server
Browse files Browse the repository at this point in the history
  • Loading branch information
craigraw committed Oct 24, 2023
1 parent b6bcdef commit 158ecd4
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/main/java/com/sparrowwallet/sparrow/net/TcpTransport.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.sparrowwallet.sparrow.net;

import com.github.arteam.simplejsonrpc.client.Transport;
import com.github.arteam.simplejsonrpc.server.JsonRpcServer;
import com.google.common.base.Splitter;
import com.google.common.net.HostAndPort;
Expand All @@ -19,6 +18,7 @@
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
Expand All @@ -40,6 +40,8 @@ public class TcpTransport implements CloseableTransport, TimeoutCounter {

private String response;

private final CountDownLatch readReadySignal = new CountDownLatch(1);

private final ReentrantLock readLock = new ReentrantLock();
private final Condition readingCondition = readLock.newCondition();

Expand Down Expand Up @@ -110,6 +112,17 @@ private void writeRequest(String request) throws IOException {
}

private String readResponse() throws IOException {
if(firstRead) {
try {
//Ensure read thread has started
if(!readReadySignal.await(2, TimeUnit.SECONDS)) {
throw new IOException("Read thread did not start");
}
} catch(InterruptedException e) {
throw new IOException("Read ready await interrupted");
}
}

try {
if(!readLock.tryLock((readTimeouts[readTimeoutIndex] * 1000L) + (requestIdCount * PER_REQUEST_READ_TIMEOUT_MILLIS), TimeUnit.MILLISECONDS)) {
readTimeoutIndex = Math.min(readTimeoutIndex + 1, readTimeouts.length - 1);
Expand Down Expand Up @@ -155,6 +168,7 @@ private String readResponse() throws IOException {

public void readInputLoop() throws ServerException {
readLock.lock();
readReadySignal.countDown();

try {
try {
Expand Down

0 comments on commit 158ecd4

Please sign in to comment.