Skip to content

Commit

Permalink
Merge pull request #3213 from christophsturm/cleanup-thread-handling
Browse files Browse the repository at this point in the history
Simplify thread handling and ensure proper they all have names
  • Loading branch information
ripcurlx authored Sep 6, 2019
2 parents ec0b657 + 4223036 commit 211eb1b
Show file tree
Hide file tree
Showing 7 changed files with 53 additions and 82 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,7 @@ public void init() {
private void start() {
isStopped = false;
log.info("AvoidStandbyModeService started");
Thread thread = new Thread(this::play);
thread.setName("AvoidStandbyModeService-thread");
thread.start();
new Thread(this::play, "AvoidStandbyModeService-thread").start();
}


Expand Down
23 changes: 5 additions & 18 deletions core/src/main/java/bisq/core/app/BisqSetup.java
Original file line number Diff line number Diff line change
Expand Up @@ -434,11 +434,8 @@ private void checkIfLocalHostNodeIsRunning() {
bisqEnvironment.getIgnoreLocalBtcNode()) {
step3();
} else {
Thread checkIfLocalHostNodeIsRunningThread = new Thread(() -> {
Thread.currentThread().setName("checkIfLocalHostNodeIsRunningThread");
Socket socket = null;
try {
socket = new Socket();
new Thread(() -> {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(InetAddresses.forString("127.0.0.1"),
BisqEnvironment.getBaseCurrencyNetwork().getParameters().getPort()), 5000);
log.info("Localhost Bitcoin node detected.");
Expand All @@ -448,16 +445,8 @@ private void checkIfLocalHostNodeIsRunning() {
});
} catch (Throwable e) {
UserThread.execute(BisqSetup.this::step3);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ignore) {
}
}
}
});
checkIfLocalHostNodeIsRunningThread.start();
}, "checkIfLocalHostNodeIsRunningThread").start();
}
}

Expand All @@ -474,9 +463,8 @@ private void checkCryptoSetup() {
// If users compile themselves they might miss that step and then would get an exception in the trade.
// To avoid that we add here at startup a sample encryption and signing to see if it don't causes an exception.
// See: https://github.com/bisq-network/exchange/blob/master/doc/build.md#7-enable-unlimited-strength-for-cryptographic-keys
Thread checkCryptoThread = new Thread(() -> {
new Thread(() -> {
try {
Thread.currentThread().setName("checkCryptoThread");
// just use any simple dummy msg
Ping payload = new Ping(1, 1);
SealedAndSigned sealedAndSigned = EncryptionService.encryptHybridWithSignature(payload,
Expand All @@ -496,8 +484,7 @@ private void checkCryptoSetup() {
if (cryptoSetupFailedHandler != null)
cryptoSetupFailedHandler.accept(msg);
}
});
checkCryptoThread.start();
}, "checkCryptoThread").start();
}

private void startP2pNetworkAndWallet() {
Expand Down
50 changes: 22 additions & 28 deletions core/src/main/java/bisq/core/app/SetupUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,49 +49,43 @@ public static void checkCryptoSetup(KeyRing keyRing, EncryptionService encryptio
// If users compile themselves they might miss that step and then would get an exception in the trade.
// To avoid that we add here at startup a sample encryption and signing to see if it don't causes an exception.
// See: https://github.com/bisq-network/exchange/blob/master/doc/build.md#7-enable-unlimited-strength-for-cryptographic-keys
Thread checkCryptoThread = new Thread() {
@Override
public void run() {
try {
Thread.currentThread().setName("checkCryptoThread");
// just use any simple dummy msg
Ping payload = new Ping(1, 1);
SealedAndSigned sealedAndSigned = EncryptionService.encryptHybridWithSignature(payload,
keyRing.getSignatureKeyPair(), keyRing.getPubKeyRing().getEncryptionPubKey());
DecryptedDataTuple tuple = encryptionService.decryptHybridWithSignature(sealedAndSigned,
keyRing.getEncryptionKeyPair().getPrivate());
if (tuple.getNetworkEnvelope() instanceof Ping &&
((Ping) tuple.getNetworkEnvelope()).getNonce() == payload.getNonce() &&
((Ping) tuple.getNetworkEnvelope()).getLastRoundTripTime() == payload.getLastRoundTripTime()) {
log.debug("Crypto test succeeded");
Thread checkCryptoThread = new Thread(() -> {
try {
// just use any simple dummy msg
Ping payload = new Ping(1, 1);
SealedAndSigned sealedAndSigned = EncryptionService.encryptHybridWithSignature(payload,
keyRing.getSignatureKeyPair(), keyRing.getPubKeyRing().getEncryptionPubKey());
DecryptedDataTuple tuple = encryptionService.decryptHybridWithSignature(sealedAndSigned,
keyRing.getEncryptionKeyPair().getPrivate());
if (tuple.getNetworkEnvelope() instanceof Ping &&
((Ping) tuple.getNetworkEnvelope()).getNonce() == payload.getNonce() &&
((Ping) tuple.getNetworkEnvelope()).getLastRoundTripTime() == payload.getLastRoundTripTime()) {
log.debug("Crypto test succeeded");

UserThread.execute(resultHandler::handleResult);
} else {
errorHandler.accept(new CryptoException("Payload not correct after decryption"));
}
} catch (CryptoException | ProtobufferException e) {
log.error(e.toString());
e.printStackTrace();
errorHandler.accept(e);
UserThread.execute(resultHandler::handleResult);
} else {
errorHandler.accept(new CryptoException("Payload not correct after decryption"));
}
} catch (CryptoException | ProtobufferException e) {
log.error(e.toString());
e.printStackTrace();
errorHandler.accept(e);
}
};
}, "checkCryptoThread");
checkCryptoThread.start();
}

public static BooleanProperty readFromResources(P2PDataStorage p2PDataStorage) {
BooleanProperty result = new SimpleBooleanProperty();
Thread thread = new Thread(() -> {
Thread.currentThread().setName("readFromResourcesThread");
new Thread(() -> {
// Used to load different files per base currency (EntryMap_BTC_MAINNET, EntryMap_LTC,...)
final BaseCurrencyNetwork baseCurrencyNetwork = BisqEnvironment.getBaseCurrencyNetwork();
final String postFix = "_" + baseCurrencyNetwork.name();
long ts = new Date().getTime();
p2PDataStorage.readFromResources(postFix);
log.info("readFromResources took {} ms", (new Date().getTime() - ts));
UserThread.execute(() -> result.set(true));
});
thread.start();
}, "readFromResourcesThread").start();
return result;
}
}
3 changes: 1 addition & 2 deletions core/src/main/java/bisq/core/btc/setup/WalletConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -561,13 +561,12 @@ private Wallet createWallet(BisqKeyChainGroup keyChainGroup, boolean isBsqWallet

private void installShutdownHook() {
if (autoStop) Runtime.getRuntime().addShutdownHook(new Thread(() -> {
Thread.currentThread().setName("ShutdownHook");
try {
WalletConfig.this.stopAsync();
WalletConfig.this.awaitTerminated();
} catch (Throwable ignore) {
}
}));
}, "WalletConfig ShutdownHook"));
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,7 @@ public Optional<DownloadTask> download(String version) {

public VerifyTask verify(List<FileDescriptor> fileDescriptors) {
VerifyTask verifyTask = new VerifyTask(fileDescriptors);
Thread th = new Thread(verifyTask);
th.start();
new Thread(verifyTask, "BisqInstaller VerifyTask").start();
// TODO: check for problems when creating task
return verifyTask;
}
Expand All @@ -120,8 +119,7 @@ private static DownloadTask downloadFiles(List<FileDescriptor> fileDescriptors,
if (saveDir == null)
saveDir = Utilities.getDownloadOfHomeDir();
DownloadTask task = new DownloadTask(fileDescriptors, saveDir);
Thread th = new Thread(task);
th.start();
new Thread(task, "BisqInstaller DownloadTask").start();
// TODO: check for problems when creating task
return task;
}
Expand Down
44 changes: 20 additions & 24 deletions monitor/src/main/java/bisq/monitor/Monitor.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
import bisq.monitor.metric.P2PMarketStats;
import bisq.monitor.metric.P2PNetworkLoad;
import bisq.monitor.metric.P2PRoundTripTime;
import bisq.monitor.metric.P2PSeedNodeSnapshot;
import bisq.monitor.metric.PriceNodeStats;
import bisq.monitor.metric.TorHiddenServiceStartupTime;
import bisq.monitor.metric.TorRoundTripTime;
import bisq.monitor.metric.TorStartupTime;
import bisq.monitor.metric.P2PSeedNodeSnapshot;
import bisq.monitor.reporter.ConsoleReporter;
import bisq.monitor.reporter.GraphiteReporter;

Expand Down Expand Up @@ -114,33 +114,29 @@ private void start() throws Throwable {
configure();

// exit Metrics gracefully on shutdown
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
// set the name of the Thread for debugging purposes
setName("shutdownHook");

log.info("system shutdown initiated");

log.info("shutting down active metrics...");
Metric.haltAllMetrics();

try {
log.info("shutting down tor...");
Tor tor = Tor.getDefault();
checkNotNull(tor, "tor must not be null");
tor.shutdown();
} catch (Throwable ignore) {
}

log.info("system halt");
}
});
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
// set the name of the Thread for debugging purposes
log.info("system shutdown initiated");

log.info("shutting down active metrics...");
Metric.haltAllMetrics();

try {
log.info("shutting down tor...");
Tor tor = Tor.getDefault();
checkNotNull(tor, "tor must not be null");
tor.shutdown();
} catch (Throwable ignore) {
}

log.info("system halt");
}, "Monitor Shutdown Hook ")
);
}

/**
* Reload the configuration from disk.
*
*
* @throws Exception if something goes wrong
*/
private void configure() throws Exception {
Expand Down
5 changes: 2 additions & 3 deletions p2p/src/main/java/bisq/network/p2p/network/Connection.java
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ public static int getPermittedMessageSize() {
private final ConnectionListener connectionListener;
@Getter
private final String uid;
private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
private final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "Connection.java executor-service"));
// holder of state shared between InputHandler and Connection
@Getter
private final Statistic statistic;
Expand Down Expand Up @@ -489,7 +489,6 @@ public void shutDown(CloseConnectionReason closeConnectionReason, @Nullable Runn

if (closeConnectionReason.sendCloseMessage) {
new Thread(() -> {
Thread.currentThread().setName("Connection:SendCloseConnectionMessage-" + this.uid);
try {
String reason = closeConnectionReason == CloseConnectionReason.RULE_VIOLATION ?
getRuleViolation().name() : closeConnectionReason.name();
Expand All @@ -506,7 +505,7 @@ public void shutDown(CloseConnectionReason closeConnectionReason, @Nullable Runn
stopped = true;
UserThread.execute(() -> doShutDown(closeConnectionReason, shutDownCompleteHandler));
}
}).start();
}, "Connection:SendCloseConnectionMessage-" + this.uid).start();
} else {
stopped = true;
doShutDown(closeConnectionReason, shutDownCompleteHandler);
Expand Down

0 comments on commit 211eb1b

Please sign in to comment.