本文整理汇总了Java中org.bitcoinj.utils.Threading类的典型用法代码示例。如果您正苦于以下问题:Java Threading类的具体用法?Java Threading怎么用?Java Threading使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Threading类属于org.bitcoinj.utils包,在下文中一共展示了Threading类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: watchCloseConfirmations
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
protected void watchCloseConfirmations() {
// When we see the close transaction get enough confirmations, we can just delete the record
// of this channel along with the refund tx from the wallet, because we're not going to need
// any of that any more.
final TransactionConfidence confidence = storedChannel.close.getConfidence();
int numConfirms = Context.get().getEventHorizon();
ListenableFuture<TransactionConfidence> future = confidence.getDepthFuture(numConfirms, Threading.SAME_THREAD);
Futures.addCallback(future, new FutureCallback<TransactionConfidence>() {
@Override
public void onSuccess(TransactionConfidence result) {
deleteChannelFromWallet();
}
@Override
public void onFailure(Throwable t) {
Throwables.propagate(t);
}
});
}
示例2: receiveContractMessage
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
@GuardedBy("lock")
private void receiveContractMessage(Protos.TwoWayChannelMessage msg) throws VerificationException {
checkState(majorVersion == 1 || majorVersion == 2);
checkState(step == InitStep.WAITING_ON_CONTRACT && msg.hasProvideContract());
log.info("Got contract, broadcasting and responding with CHANNEL_OPEN");
final Protos.ProvideContract providedContract = msg.getProvideContract();
if (majorVersion == 2) {
state = new PaymentChannelV2ServerState(broadcaster, wallet, myKey, expireTime);
checkState(providedContract.hasClientKey(), "ProvideContract didn't have a client key in protocol v2");
((PaymentChannelV2ServerState)state).provideClientKey(providedContract.getClientKey().toByteArray());
}
//TODO notify connection handler that timeout should be significantly extended as we wait for network propagation?
final Transaction contract = wallet.getParams().getDefaultSerializer().makeTransaction(providedContract.getTx().toByteArray());
step = InitStep.WAITING_ON_MULTISIG_ACCEPTANCE;
state.provideContract(contract)
.addListener(new Runnable() {
@Override
public void run() {
multisigContractPropogated(providedContract, contract.getHash());
}
}, Threading.SAME_THREAD);
}
示例3: Peer
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
/**
* <p>Construct a peer that reads/writes from the given block chain. Transactions stored in a {@link org.bitcoinj.core.TxConfidenceTable}
* will have their confidence levels updated when a peer announces it, to reflect the greater likelyhood that
* the transaction is valid.</p>
*
* <p>Note that this does <b>NOT</b> make a connection to the given remoteAddress, it only creates a handler for a
* connection. If you want to create a one-off connection, create a Peer and pass it to
* {@link org.bitcoinj.net.NioClientManager#openConnection(java.net.SocketAddress, StreamConnection)}
* or
* {@link org.bitcoinj.net.NioClient#NioClient(java.net.SocketAddress, StreamConnection, int)}.</p>
*
* <p>The remoteAddress provided should match the remote address of the peer which is being connected to, and is
* used to keep track of which peers relayed transactions and offer more descriptive logging.</p>
*/
public Peer(NetworkParameters params, VersionMessage ver, PeerAddress remoteAddress,
@Nullable AbstractBlockChain chain, int downloadTxDependencyDepth) {
super(params, remoteAddress);
this.params = Preconditions.checkNotNull(params);
this.versionMessage = Preconditions.checkNotNull(ver);
this.vDownloadTxDependencyDepth = chain != null ? downloadTxDependencyDepth : 0;
this.blockChain = chain; // Allowed to be null.
this.vDownloadData = chain != null;
this.getDataFutures = new CopyOnWriteArrayList<>();
this.getAddrFutures = new LinkedList<>();
this.fastCatchupTimeSecs = params.getGenesisBlock().getTimeSeconds();
this.pendingPings = new CopyOnWriteArrayList<>();
this.vMinProtocolVersion = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.PONG);
this.wallets = new CopyOnWriteArrayList<>();
this.context = Context.get();
this.versionHandshakeFuture.addListener(new Runnable() {
@Override
public void run() {
versionHandshakeComplete();
}
}, Threading.SAME_THREAD);
}
示例4: processGetData
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
protected void processGetData(GetDataMessage getdata) {
log.info("{}: Received getdata message: {}", getAddress(), getdata.toString());
ArrayList<Message> items = new ArrayList<>();
for (ListenerRegistration<GetDataEventListener> registration : getDataEventListeners) {
if (registration.executor != Threading.SAME_THREAD) continue;
List<Message> listenerItems = registration.listener.getData(this, getdata);
if (listenerItems == null) continue;
items.addAll(listenerItems);
}
if (items.isEmpty()) {
return;
}
log.info("{}: Sending {} items gathered from listeners to peer", getAddress(), items.size());
for (Message item : items) {
sendMessage(item);
}
}
示例5: addWallet
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
/**
* <p>Link the given wallet to this PeerGroup. This is used for three purposes:</p>
*
* <ol>
* <li>So the wallet receives broadcast transactions.</li>
* <li>Announcing pending transactions that didn't get into the chain yet to our peers.</li>
* <li>Set the fast catchup time using {@link PeerGroup#setFastCatchupTimeSecs(long)}, to optimize chain
* download.</li>
* </ol>
*
* <p>Note that this should be done before chain download commences because if you add a wallet with keys earlier
* than the current chain head, the relevant parts of the chain won't be redownloaded for you.</p>
*
* <p>The Wallet will have an event listener registered on it, so to avoid leaks remember to use
* {@link PeerGroup#removeWallet(Wallet)} on it if you wish to keep the Wallet but lose the PeerGroup.</p>
*/
public void addWallet(Wallet wallet) {
lock.lock();
try {
checkNotNull(wallet);
checkState(!wallets.contains(wallet));
wallets.add(wallet);
wallet.setTransactionBroadcaster(this);
wallet.addCoinsReceivedEventListener(Threading.SAME_THREAD, walletCoinsReceivedEventListener);
wallet.addKeyChainEventListener(Threading.SAME_THREAD, walletKeyEventListener);
wallet.addScriptChangeEventListener(Threading.SAME_THREAD, walletScriptEventListener);
addPeerFilterProvider(wallet);
for (Peer peer : peers) {
peer.addWallet(wallet);
}
} finally {
lock.unlock();
}
}
示例6: startBlockChainDownload
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
/**
* <p>Start downloading the blockchain from the first available peer.</p>
*
* <p>If no peers are currently connected, the download will be started once a peer starts. If the peer dies,
* the download will resume with another peer.</p>
*
* @param listener a listener for chain download events, may not be null
*/
public void startBlockChainDownload(PeerDataEventListener listener) {
lock.lock();
try {
if (downloadPeer != null) {
if (this.downloadListener != null) {
removeDataEventListenerFromPeer(downloadPeer, this.downloadListener);
}
if (listener != null) {
addDataEventListenerToPeer(Threading.USER_THREAD, downloadPeer, listener);
}
}
this.downloadListener = listener;
// TODO: be more nuanced about which peer to download from. We can also try
// downloading from multiple peers and handle the case when a new peer comes along
// with a longer chain after we thought we were done.
if (!peers.isEmpty()) {
startBlockChainDownloadFromPeer(peers.iterator().next()); // Will add the new download listener
}
} finally {
lock.unlock();
}
}
示例7: setDownloadPeer
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
private void setDownloadPeer(@Nullable Peer peer) {
lock.lock();
try {
if (downloadPeer == peer)
return;
if (downloadPeer != null) {
log.info("Unsetting download peer: {}", downloadPeer);
if (downloadListener != null) {
removeDataEventListenerFromPeer(downloadPeer, downloadListener);
}
downloadPeer.setDownloadData(false);
}
downloadPeer = peer;
if (downloadPeer != null) {
log.info("Setting download peer: {}", downloadPeer);
if (downloadListener != null) {
addDataEventListenerToPeer(Threading.SAME_THREAD, peer, downloadListener);
}
downloadPeer.setDownloadData(true);
if (chain != null)
downloadPeer.setDownloadParameters(fastCatchupTimeSecs, bloomFilterMerger.getLastFilter() != null);
}
} finally {
lock.unlock();
}
}
示例8: startBlockChainDownloadFromPeer
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
private void startBlockChainDownloadFromPeer(Peer peer) {
lock.lock();
try {
setDownloadPeer(peer);
if (chainDownloadSpeedCalculator == null) {
// Every second, run the calculator which will log how fast we are downloading the chain.
chainDownloadSpeedCalculator = new ChainDownloadSpeedCalculator();
executor.scheduleAtFixedRate(chainDownloadSpeedCalculator, 1, 1, TimeUnit.SECONDS);
}
peer.addBlocksDownloadedEventListener(Threading.SAME_THREAD, chainDownloadSpeedCalculator);
// startBlockChainDownload will setDownloadData(true) on itself automatically.
peer.startBlockChainDownload();
} finally {
lock.unlock();
}
}
示例9: exceptionCaught
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
/** Catch any exceptions, logging them and then closing the channel. */
private void exceptionCaught(Exception e) {
PeerAddress addr = getAddress();
String s = addr == null ? "?" : addr.toString();
if (e instanceof ConnectException || e instanceof IOException) {
// Short message for network errors
log.info(s + " - " + e.getMessage());
} else {
log.warn(s + " - ", e);
Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
if (handler != null)
handler.uncaughtException(Thread.currentThread(), e);
}
close();
}
示例10: onResume
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
@Override
public void onResume() {
super.onResume();
resolver.registerContentObserver(AddressBookProvider.contentUri(activity.getPackageName()), true,
addressBookObserver);
config.registerOnSharedPreferenceChangeListener(this);
final Bundle args = new Bundle();
args.putSerializable(ARG_DIRECTION, direction);
loaderManager.initLoader(ID_TRANSACTION_LOADER, args, this);
wallet.addCoinsReceivedEventListener(Threading.SAME_THREAD, transactionChangeListener);
wallet.addCoinsSentEventListener(Threading.SAME_THREAD, transactionChangeListener);
wallet.addChangeEventListener(Threading.SAME_THREAD, transactionChangeListener);
wallet.addTransactionConfidenceEventListener(Threading.SAME_THREAD, transactionChangeListener);
updateView();
}
示例11: Peer
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
/**
* <p>Construct a peer that reads/writes from the given block chain. Transactions stored in a {@link org.bitcoinj.core.TxConfidenceTable}
* will have their confidence levels updated when a peer announces it, to reflect the greater likelyhood that
* the transaction is valid.</p>
*
* <p>Note that this does <b>NOT</b> make a connection to the given remoteAddress, it only creates a handler for a
* connection. If you want to create a one-off connection, create a Peer and pass it to
* {@link org.bitcoinj.net.NioClientManager#openConnection(java.net.SocketAddress, StreamConnection)}
* or
* {@link org.bitcoinj.net.NioClient#NioClient(java.net.SocketAddress, StreamConnection, int)}.</p>
*
* <p>The remoteAddress provided should match the remote address of the peer which is being connected to, and is
* used to keep track of which peers relayed transactions and offer more descriptive logging.</p>
*/
public Peer(NetworkParameters params, VersionMessage ver, PeerAddress remoteAddress,
@Nullable AbstractBlockChain chain, int downloadTxDependencyDepth) {
super(params, remoteAddress);
this.params = Preconditions.checkNotNull(params);
this.versionMessage = Preconditions.checkNotNull(ver);
this.vDownloadTxDependencyDepth = chain != null ? downloadTxDependencyDepth : 0;
this.blockChain = chain; // Allowed to be null.
this.vDownloadData = chain != null;
this.getDataFutures = new CopyOnWriteArrayList<GetDataRequest>();
this.getAddrFutures = new LinkedList<SettableFuture<AddressMessage>>();
this.fastCatchupTimeSecs = params.getGenesisBlock().getTimeSeconds();
this.pendingPings = new CopyOnWriteArrayList<PendingPing>();
this.vMinProtocolVersion = params.getProtocolVersionNum(NetworkParameters.ProtocolVersion.PONG);
this.wallets = new CopyOnWriteArrayList<Wallet>();
this.context = Context.get();
this.versionHandshakeFuture.addListener(new Runnable() {
@Override
public void run() {
versionHandshakeComplete();
}
}, Threading.SAME_THREAD);
}
示例12: processGetData
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
protected void processGetData(GetDataMessage getdata) {
log.info("{}: Received getdata message: {}", getAddress(), getdata.toString());
ArrayList<Message> items = new ArrayList<Message>();
for (ListenerRegistration<GetDataEventListener> registration : getDataEventListeners) {
if (registration.executor != Threading.SAME_THREAD) continue;
List<Message> listenerItems = registration.listener.getData(this, getdata);
if (listenerItems == null) continue;
items.addAll(listenerItems);
}
if (items.isEmpty()) {
return;
}
log.info("{}: Sending {} items gathered from listeners to peer", getAddress(), items.size());
for (Message item : items) {
sendMessage(item);
}
}
示例13: events
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
@Test
public void events() throws Exception {
// Check that events are registered with the right chains and that if a chain is added, it gets the event
// listeners attached properly even post-hoc.
final AtomicReference<ECKey> ran = new AtomicReference<ECKey>(null);
final KeyChainEventListener listener = new KeyChainEventListener() {
@Override
public void onKeysAdded(List<ECKey> keys) {
ran.set(keys.get(0));
}
};
group.addEventListener(listener, Threading.SAME_THREAD);
ECKey key = group.freshKey(KeyChain.KeyPurpose.RECEIVE_FUNDS);
assertEquals(key, ran.getAndSet(null));
ECKey key2 = new ECKey();
group.importKeys(key2);
assertEquals(key2, ran.getAndSet(null));
group.removeEventListener(listener);
ECKey key3 = new ECKey();
group.importKeys(key3);
assertNull(ran.get());
}
示例14: cleanupCommon
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
private Transaction cleanupCommon(Address destination) throws Exception {
receiveATransaction(wallet, myAddress);
Coin v2 = valueOf(0, 50);
SendRequest req = SendRequest.to(destination, v2);
wallet.completeTx(req);
Transaction t2 = req.tx;
// Broadcast the transaction and commit.
broadcastAndCommit(wallet, t2);
// At this point we have one pending and one spent
Coin v1 = valueOf(0, 10);
Transaction t = sendMoneyToWallet(null, v1, myAddress);
Threading.waitForUserCode();
sendMoneyToWallet(null, t);
assertEquals("Wrong number of PENDING", 2, wallet.getPoolSize(Pool.PENDING));
assertEquals("Wrong number of UNSPENT", 0, wallet.getPoolSize(Pool.UNSPENT));
assertEquals("Wrong number of ALL", 3, wallet.getTransactions(true).size());
assertEquals(valueOf(0, 60), wallet.getBalance(Wallet.BalanceType.ESTIMATED));
// Now we have another incoming pending
return t;
}
示例15: saveNow
import org.bitcoinj.utils.Threading; //导入依赖的package包/类
/** If auto saving is enabled, do an immediate sync write to disk ignoring any delays. */
public void saveNow() {
lock.lock();
try {
WalletFiles files = vFileManager;
if (files != null) {
try {
files.saveNow(); // This calls back into saveToFile().
} catch (IOException e) {
// Can't really do much at this point, just let the API user know.
log.error("Failed to save wallet to disk!", e);
Thread.UncaughtExceptionHandler handler = Threading.uncaughtExceptionHandler;
if (handler != null)
handler.uncaughtException(Thread.currentThread(), e);
}
}
} finally {
lock.unlock();
}
}