Java Code Examples for java.util.concurrent.locks.Condition#awaitUninterruptibly()
The following examples show how to use
java.util.concurrent.locks.Condition#awaitUninterruptibly() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MultiLock.java From unitime with Apache License 2.0 | 6 votes |
public UnlockAll lockAll() { iLock.lock(); try { iLog.debug("Locking all ..."); while (iAllLocked != null) iAllLocked.awaitUninterruptibly(); iAllLocked = iLock.newCondition(); while (!iIndividualLocks.isEmpty()) { Condition otherCondition = iIndividualLocks.values().iterator().next(); otherCondition.awaitUninterruptibly(); } iLog.debug("Locked: all"); return new UnlockAll(); } finally { iLock.unlock(); } }
Example 2
Source File: MultiLock.java From unitime with Apache License 2.0 | 6 votes |
public Unlock lock(Collection<Long> ids) { iLock.lock(); try { if (ids == null || ids.isEmpty()) return new Unlock(ids); iLog.debug("Locking " + ids + " ..."); Condition otherCondition = null; while ((otherCondition = hasLock(ids)) != null) otherCondition.awaitUninterruptibly(); Condition myCondition = iLock.newCondition(); for (Long id: ids) iIndividualLocks.put(id, myCondition); iLog.debug("Locked: " + ids); return new Unlock(ids); } finally { iLock.unlock(); } }
Example 3
Source File: ReentrantTransactionDispatcher.java From xodus with Apache License 2.0 | 6 votes |
private void waitForPermits(@NotNull final Thread thread, @NotNull final NavigableMap<Long, Condition> queue, final int permits, final int currentThreadPermits) { final Condition condition = criticalSection.newCondition(); final long currentOrder = acquireOrder++; queue.put(currentOrder, condition); while (acquiredPermits > availablePermits - permits || queue.firstKey() != currentOrder) { condition.awaitUninterruptibly(); } queue.pollFirstEntry(); acquiredPermits += permits; threadPermits.put(thread, currentThreadPermits + permits); if (acquiredPermits < availablePermits) { notifyNextWaiters(); } }
Example 4
Source File: ShortCircuitCache.java From hadoop with Apache License 2.0 | 4 votes |
ClientMmap getOrCreateClientMmap(ShortCircuitReplica replica, boolean anchored) { Condition newCond; lock.lock(); try { while (replica.mmapData != null) { if (replica.mmapData instanceof MappedByteBuffer) { ref(replica); MappedByteBuffer mmap = (MappedByteBuffer)replica.mmapData; return new ClientMmap(replica, mmap, anchored); } else if (replica.mmapData instanceof Long) { long lastAttemptTimeMs = (Long)replica.mmapData; long delta = Time.monotonicNow() - lastAttemptTimeMs; if (delta < mmapRetryTimeoutMs) { if (LOG.isTraceEnabled()) { LOG.trace(this + ": can't create client mmap for " + replica + " because we failed to " + "create one just " + delta + "ms ago."); } return null; } if (LOG.isTraceEnabled()) { LOG.trace(this + ": retrying client mmap for " + replica + ", " + delta + " ms after the previous failure."); } } else if (replica.mmapData instanceof Condition) { Condition cond = (Condition)replica.mmapData; cond.awaitUninterruptibly(); } else { Preconditions.checkState(false, "invalid mmapData type %s", replica.mmapData.getClass().getName()); } } newCond = lock.newCondition(); replica.mmapData = newCond; } finally { lock.unlock(); } MappedByteBuffer map = replica.loadMmapInternal(); lock.lock(); try { if (map == null) { replica.mmapData = Long.valueOf(Time.monotonicNow()); newCond.signalAll(); return null; } else { outstandingMmapCount++; replica.mmapData = map; ref(replica); newCond.signalAll(); return new ClientMmap(replica, map, anchored); } } finally { lock.unlock(); } }
Example 5
Source File: ShortCircuitCache.java From big-c with Apache License 2.0 | 4 votes |
ClientMmap getOrCreateClientMmap(ShortCircuitReplica replica, boolean anchored) { Condition newCond; lock.lock(); try { while (replica.mmapData != null) { if (replica.mmapData instanceof MappedByteBuffer) { ref(replica); MappedByteBuffer mmap = (MappedByteBuffer)replica.mmapData; return new ClientMmap(replica, mmap, anchored); } else if (replica.mmapData instanceof Long) { long lastAttemptTimeMs = (Long)replica.mmapData; long delta = Time.monotonicNow() - lastAttemptTimeMs; if (delta < mmapRetryTimeoutMs) { if (LOG.isTraceEnabled()) { LOG.trace(this + ": can't create client mmap for " + replica + " because we failed to " + "create one just " + delta + "ms ago."); } return null; } if (LOG.isTraceEnabled()) { LOG.trace(this + ": retrying client mmap for " + replica + ", " + delta + " ms after the previous failure."); } } else if (replica.mmapData instanceof Condition) { Condition cond = (Condition)replica.mmapData; cond.awaitUninterruptibly(); } else { Preconditions.checkState(false, "invalid mmapData type %s", replica.mmapData.getClass().getName()); } } newCond = lock.newCondition(); replica.mmapData = newCond; } finally { lock.unlock(); } MappedByteBuffer map = replica.loadMmapInternal(); lock.lock(); try { if (map == null) { replica.mmapData = Long.valueOf(Time.monotonicNow()); newCond.signalAll(); return null; } else { outstandingMmapCount++; replica.mmapData = map; ref(replica); newCond.signalAll(); return new ClientMmap(replica, map, anchored); } } finally { lock.unlock(); } }
Example 6
Source File: JobCreatorHolderTest.java From android-job with Apache License 2.0 | 4 votes |
@Test public void createJobSucceedsWhenCreatorListIsModifiedConcurrently() { // This test verifies that modifying the list of job-creators while // another thread is in the middle of JobCreatorHolder#createJob(String) // is safe, in that createJob will finish unexceptionally. // // We'll test thread-safety by beginning iteration through the // job-creator list, then adding another creator while the iterator // is active. If we are thread-safe, then iteration will complete // without an exception. // // To coordinate this, we'll need a custom job creator that blocks // until it receives a signal to continue. A "reader" thread will // invoke "createJob", iterating over the list, and blocking. While // the reader is blocked, a "mutator" thread will modify the creator // list, then signal the reader thread to resume. Any // ConcurrentModificationException will be caught and stored. When // both threads are finished, we can verify that no error was thrown. final Lock lock = new ReentrantLock(); final Condition listModified = lock.newCondition(); final Condition iterationStarted = lock.newCondition(); final AtomicReference<Throwable> error = new AtomicReference<>(); final AtomicBoolean isIteratorActive = new AtomicBoolean(false); class BlockingJobCreator implements JobCreator { @Override public Job create(@NonNull String tag) { lock.lock(); try { isIteratorActive.set(true); iterationStarted.signal(); listModified.awaitUninterruptibly(); } finally { lock.unlock(); } return null; } } class Mutator extends Thread { @Override public void run() { waitUntilIterationStarted(); holder.addJobCreator(mockJobCreator); signalListModified(); } private void waitUntilIterationStarted() { lock.lock(); try { if (!isIteratorActive.get()) { iterationStarted.awaitUninterruptibly(); } } finally { lock.unlock(); } } private void signalListModified() { lock.lock(); try { listModified.signal(); } finally { lock.unlock(); } } } class Reader extends Thread { @Override public void run() { try { holder.createJob("SOME_JOB_TAG"); } catch (Throwable t) { error.set(t); } } } holder.addJobCreator(new BlockingJobCreator()); Mutator mutator = new Mutator(); Reader reader = new Reader(); reader.start(); mutator.start(); join(mutator); join(reader); assertThat(error.get()).isNull(); }
Example 7
Source File: SendHDMBitcoinPanel.java From bither-desktop-java with Apache License 2.0 | 4 votes |
@Override public List<TransactionSignature> getOtherSignature(int addressIndex, CharSequence password, List<byte[]> unsignHash, Tx tx) { List<TransactionSignature> transactionSignatureList = new ArrayList<TransactionSignature>(); try { HDMBId hdmbId = HDMBId.getHDMBidFromDb(); byte[] decryptedPassword = hdmbId.decryptHDMBIdPassword(password); SignatureHDMApi signatureHDMApi = new SignatureHDMApi(HDMBId.getHDMBidFromDb() .getAddress(), addressIndex, decryptedPassword, unsignHash); signatureHDMApi.handleHttpPost(); List<byte[]> bytesList = signatureHDMApi.getResult(); for (byte[] bytes : bytesList) { TransactionSignature transactionSignature = new TransactionSignature(ECKey .ECDSASignature.decodeFromDER(bytes), TransactionSignature.SigHash .ALL, false); transactionSignatureList.add(transactionSignature); } } catch (Exception e) { if (e instanceof Http400Exception) { if (((Http400Exception) e).getErrorCode() == HttpSetting.PasswordWrong) { toChangePassword = false; final ReentrantLock lock = new ReentrantLock(); final Condition changePasswordCondition = lock.newCondition(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { dp.dispose(); DialogConfirmTask dialogConfirmTask = new DialogConfirmTask(LocaliserUtils.getString("hdm_reset_server_password_password_wrong_confirm"), new Runnable() { @Override public void run() { toChangePassword = true; try { lock.lock(); changePasswordCondition.signal(); } finally { lock.unlock(); } } }, new Runnable() { @Override public void run() { toChangePassword = false; try { lock.lock(); changePasswordCondition.signal(); } finally { lock.unlock(); } } }); dialogConfirmTask.pack(); dialogConfirmTask.setVisible(true); } }); try { lock.lock(); changePasswordCondition.awaitUninterruptibly(); } finally { lock.unlock(); } if (!toChangePassword) { throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion(); } resetServerPasswordUtil.setPassword(password); if (!resetServerPasswordUtil.changePassword()) { throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion(); } return getOtherSignature(addressIndex, password, unsignHash, tx); } else { throw new CompleteTransactionRunnable.HDMServerSignException(LocaliserUtils.getString( "hdm_address_sign_tx_server_error")); } } else if (e instanceof KeyCrypterException) { throw new PasswordException("hdm password decrypting error"); } else { throw new RuntimeException(e); } } return transactionSignatureList; }
Example 8
Source File: HdmSendActivity.java From bither-android with Apache License 2.0 | 4 votes |
@Override public List<TransactionSignature> getOtherSignature(int addressIndex, CharSequence password, List<byte[]> unsignHash, Tx tx) { List<TransactionSignature> transactionSignatureList = new ArrayList<TransactionSignature>(); try { HDMBId hdmbId = HDMBId.getHDMBidFromDb(); byte[] decryptedPassword = hdmbId.decryptHDMBIdPassword(password); SignatureHDMApi signatureHDMApi = new SignatureHDMApi(HDMBId.getHDMBidFromDb() .getAddress(), addressIndex, decryptedPassword, unsignHash); signatureHDMApi.handleHttpPost(); List<byte[]> bytesList = signatureHDMApi.getResult(); for (byte[] bytes : bytesList) { TransactionSignature transactionSignature = new TransactionSignature(ECKey .ECDSASignature.decodeFromDER(bytes), TransactionSignature.SigHash .ALL, false); transactionSignatureList.add(transactionSignature); } } catch (Exception e) { if (e instanceof Http400Exception) { if (((Http400Exception) e).getErrorCode() == HttpSetting.PasswordWrong) { toChangePassword = false; final ReentrantLock lock = new ReentrantLock(); final Condition changePasswordCondition = lock.newCondition(); runOnUiThread(new Runnable() { @Override public void run() { if (dp.isShowing()) { dp.dismiss(); } new DialogConfirmTask(HdmSendActivity.this, getString(R.string.hdm_reset_server_password_password_wrong_confirm), new Runnable() { @Override public void run() { toChangePassword = true; try { lock.lock(); changePasswordCondition.signal(); } finally { lock.unlock(); } } }, new Runnable() { @Override public void run() { toChangePassword = false; try { lock.lock(); changePasswordCondition.signal(); } finally { lock.unlock(); } } }).show(); } }); try { lock.lock(); changePasswordCondition.awaitUninterruptibly(); } finally { lock.unlock(); } if (!toChangePassword) { throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion(); } resetServerPasswordUtil.setPassword(password); if (!resetServerPasswordUtil.changePassword()) { throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion(); } return getOtherSignature(addressIndex, password, unsignHash, tx); } else { throw new CompleteTransactionRunnable.HDMServerSignException(R.string .hdm_address_sign_tx_server_error); } } else if (e instanceof KeyCrypterException) { throw new PasswordException("hdm password decrypting error"); } else { throw new RuntimeException(e); } } return transactionSignatureList; }
Example 9
Source File: SendHDMBitcoinPanel.java From bither-desktop-java with Apache License 2.0 | 4 votes |
@Override public List<TransactionSignature> getOtherSignature(int addressIndex, CharSequence password, List<byte[]> unsignHash, Tx tx) { List<TransactionSignature> transactionSignatureList = new ArrayList<TransactionSignature>(); try { HDMBId hdmbId = HDMBId.getHDMBidFromDb(); byte[] decryptedPassword = hdmbId.decryptHDMBIdPassword(password); SignatureHDMApi signatureHDMApi = new SignatureHDMApi(HDMBId.getHDMBidFromDb() .getAddress(), addressIndex, decryptedPassword, unsignHash); signatureHDMApi.handleHttpPost(); List<byte[]> bytesList = signatureHDMApi.getResult(); for (byte[] bytes : bytesList) { TransactionSignature transactionSignature = new TransactionSignature(ECKey .ECDSASignature.decodeFromDER(bytes), TransactionSignature.SigHash .ALL, false); transactionSignatureList.add(transactionSignature); } } catch (Exception e) { if (e instanceof Http400Exception) { if (((Http400Exception) e).getErrorCode() == HttpSetting.PasswordWrong) { toChangePassword = false; final ReentrantLock lock = new ReentrantLock(); final Condition changePasswordCondition = lock.newCondition(); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { dp.dispose(); DialogConfirmTask dialogConfirmTask = new DialogConfirmTask(LocaliserUtils.getString("hdm_reset_server_password_password_wrong_confirm"), new Runnable() { @Override public void run() { toChangePassword = true; try { lock.lock(); changePasswordCondition.signal(); } finally { lock.unlock(); } } }, new Runnable() { @Override public void run() { toChangePassword = false; try { lock.lock(); changePasswordCondition.signal(); } finally { lock.unlock(); } } }); dialogConfirmTask.pack(); dialogConfirmTask.setVisible(true); } }); try { lock.lock(); changePasswordCondition.awaitUninterruptibly(); } finally { lock.unlock(); } if (!toChangePassword) { throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion(); } resetServerPasswordUtil.setPassword(password); if (!resetServerPasswordUtil.changePassword()) { throw new CompleteTransactionRunnable.HDMSignUserCancelExcetion(); } return getOtherSignature(addressIndex, password, unsignHash, tx); } else { throw new CompleteTransactionRunnable.HDMServerSignException(LocaliserUtils.getString( "hdm_address_sign_tx_server_error")); } } else if (e instanceof KeyCrypterException) { throw new PasswordException("hdm password decrypting error"); } else { throw new RuntimeException(e); } } return transactionSignatureList; }
Example 10
Source File: Sequence.java From mongodb-async-driver with Apache License 2.0 | 4 votes |
/** * Waits for the reserved sequence to be released. * * @param wanted * The sequence to wait to be released. */ public void waitFor(final long wanted) { long releaseValue = myPaddedValue.get(RELEASE_OFFSET); while (releaseValue != wanted) { if (myLockType == LockType.LOW_LATENCY_SPIN) { long now = System.nanoTime(); final long yeildDeadline = now + YIELD_TIME_NS; releaseValue = myPaddedValue.get(RELEASE_OFFSET); while ((now < yeildDeadline) && (releaseValue != wanted)) { // Let another thread make progress. Thread.yield(); now = System.nanoTime(); releaseValue = myPaddedValue.get(RELEASE_OFFSET); } } // Block. if (releaseValue != wanted) { final Long key = Long.valueOf(wanted); Condition localCondition = myCondition; try { final int waitCount = myWaiting.incrementAndGet(); myLock.lock(); // Second tier try for FindBugs to see the unlock. try { // Check for more than 1 waiter. If so stand in line via // the waiters map. (This will wake threads in the order // they should be processed.) if (waitCount > 1) { localCondition = myLock.newCondition(); myWaiters.put(key, localCondition); } releaseValue = myPaddedValue.get(RELEASE_OFFSET); while (releaseValue != wanted) { localCondition.awaitUninterruptibly(); releaseValue = myPaddedValue.get(RELEASE_OFFSET); } } finally { if (localCondition != myCondition) { myWaiters.remove(key); } } } finally { myLock.unlock(); myWaiting.decrementAndGet(); } } } }