add exception handling to runnables

This commit is contained in:
Manfred Karrer 2015-11-03 20:56:08 +01:00
parent 4d82467fa3
commit 0b7e45ca55
15 changed files with 463 additions and 385 deletions

View file

@ -245,9 +245,18 @@ public class WalletService {
}
public void restoreSeedWords(DeterministicSeed seed, ResultHandler resultHandler, ExceptionHandler exceptionHandler) {
walletAppKit.stopAsync();
walletAppKit.awaitTerminated();
initialize(seed, resultHandler, exceptionHandler);
Context ctx = Context.get();
new Thread(() -> {
try {
Context.propagate(ctx);
walletAppKit.stopAsync();
walletAppKit.awaitTerminated();
initialize(seed, resultHandler, exceptionHandler);
} catch (Throwable t) {
t.printStackTrace();
log.error("Executing task failed. " + t.getMessage());
}
}, "RestoreWallet-%d").start();
}

View file

@ -1,5 +1,6 @@
package io.bitsquare.crypto;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.protobuf.ByteString;
import io.bitsquare.common.UserThread;
import org.bitcoinj.crypto.KeyCrypterScrypt;
@ -8,6 +9,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongycastle.crypto.params.KeyParameter;
import java.util.concurrent.*;
//TODO: Borrowed form BitcoinJ/Lighthouse. Remove Protos dependency, check complete code logic.
public class ScryptUtil {
private static final Logger log = LoggerFactory.getLogger(ScryptUtil.class);
@ -27,14 +30,31 @@ public class ScryptUtil {
}
public static void deriveKeyWithScrypt(KeyCrypterScrypt keyCrypterScrypt, String password, DeriveKeyResultHandler resultHandler) {
new Thread(() -> {
log.info("Doing key derivation");
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat("Routing-%d")
.setDaemon(true)
.build();
long start = System.currentTimeMillis();
KeyParameter aesKey = keyCrypterScrypt.deriveKey(password);
long duration = System.currentTimeMillis() - start;
log.info("Key derivation took {} msec", duration);
UserThread.execute(() -> resultHandler.handleResult(aesKey));
}).start();
ExecutorService executorService = new ThreadPoolExecutor(5, 50, 10L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(50), threadFactory);
executorService.submit(() -> {
try {
log.info("Doing key derivation");
long start = System.currentTimeMillis();
KeyParameter aesKey = keyCrypterScrypt.deriveKey(password);
long duration = System.currentTimeMillis() - start;
log.info("Key derivation took {} msec", duration);
UserThread.execute(() -> {
try {
resultHandler.handleResult(aesKey);
} catch (Throwable t) {
t.printStackTrace();
log.error("Executing task failed. " + t.getMessage());
}
});
} catch (Throwable t) {
t.printStackTrace();
log.error("Executing task failed. " + t.getMessage());
}
});
}
}

View file

@ -17,7 +17,6 @@
package io.bitsquare.trade.offer;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.inject.Inject;
import io.bitsquare.btc.TradeWalletService;
import io.bitsquare.btc.WalletService;
@ -47,10 +46,11 @@ import javax.inject.Named;
import java.io.File;
import java.time.Duration;
import java.util.Optional;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.inject.internal.util.$Preconditions.checkNotNull;
import static io.bitsquare.util.Validator.nonEmptyStringOf;
@ -70,7 +70,7 @@ public class OpenOfferManager {
private boolean shutDownRequested;
private ScheduledThreadPoolExecutor executor;
private P2PServiceListener p2PServiceListener;
private final Timer timer = new Timer();
///////////////////////////////////////////////////////////////////////////////////////////
// Constructor
@ -96,9 +96,13 @@ public class OpenOfferManager {
openOffersStorage = new Storage<>(storageDir);
this.openOffers = new TradableList<>(openOffersStorage, "OpenOffers");
init();
}
private void init() {
// In case the app did get killed the shutDown from the modules is not called, so we use a shutdown hook
Thread shutDownHookThread = new Thread(OpenOfferManager.this::shutDown, "OpenOfferManager.ShutDownHook");
Runtime.getRuntime().addShutdownHook(shutDownHookThread);
Runtime.getRuntime().addShutdownHook(new Thread(OpenOfferManager.this::shutDown,
"OpenOfferManager.ShutDownHook"));
// Handler for incoming offer availability requests
p2PService.addDecryptedMailListener((decryptedMessageWithPubKey, peerAddress) -> {
@ -155,25 +159,27 @@ public class OpenOfferManager {
}
private void startRePublishThread() {
if (p2PServiceListener != null) p2PService.removeP2PServiceListener(p2PServiceListener);
if (p2PServiceListener != null)
p2PService.removeP2PServiceListener(p2PServiceListener);
ThreadFactoryBuilder builder = new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("Re-publish offers thread")
.setPriority(Thread.MIN_PRIORITY); // Avoid competing with the GUI thread.
// An executor that starts up threads when needed and shuts them down later.
executor = new ScheduledThreadPoolExecutor(1, builder.build());
executor.setKeepAliveTime(5, TimeUnit.SECONDS);
executor.allowCoreThreadTimeOut(true);
executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
checkArgument(Offer.TTL > 120000, "Offer.TTL <= 120");
long period = Offer.TTL - 120000; // 2 min before TTL expires
executor.scheduleAtFixedRate(this::rePublishOffers, 500, period, TimeUnit.MILLISECONDS);
long period = (long) (Offer.TTL * 0.8);
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
Thread.currentThread().setName("RepublishOffers-%d");
rePublishOffers();
try {
} catch (Throwable t) {
t.printStackTrace();
log.error("Executing task failed. " + t.getMessage());
}
}
};
timer.scheduleAtFixedRate(timerTask, 500, period);
}
private void rePublishOffers() {
log.trace("rePublishOffers");
for (OpenOffer openOffer : openOffers) {
offerBookService.addOffer(openOffer.getOffer(),
() -> log.debug("Successful added offer to P2P network"),

View file

@ -51,9 +51,10 @@ public class SetupPayoutTxLockTimeReachedListener extends TradeTask {
() -> {
try {
log.debug("Block height reached " + blockHeightFuture.get().getHeight());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} catch (ExecutionException e) {
e.printStackTrace();
}
broadcastTx();
},