Java Code Examples for com.twitter.util.Promise#setValue()

The following examples show how to use com.twitter.util.Promise#setValue() . 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: DistributedLogClientImpl.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
void complete(SocketAddress address, BulkWriteResponse bulkWriteResponse) {
    super.complete(address);
    Iterator<WriteResponse> writeResponseIterator = bulkWriteResponse.getWriteResponses().iterator();
    Iterator<Promise<DLSN>> resultIterator = results.iterator();

    // Fill in errors from thrift responses.
    while (resultIterator.hasNext() && writeResponseIterator.hasNext()) {
        Promise<DLSN> result = resultIterator.next();
        WriteResponse writeResponse = writeResponseIterator.next();
        if (StatusCode.SUCCESS == writeResponse.getHeader().getCode()) {
            result.setValue(DLSN.deserialize(writeResponse.getDlsn()));
        } else {
            result.setException(DLException.of(writeResponse.getHeader()));
        }
    }

    // Should never happen, but just in case so there's some record.
    if (bulkWriteResponse.getWriteResponses().size() != data.size()) {
        logger.error("wrong number of results, response = {} records = ", bulkWriteResponse.getWriteResponses().size(), data.size());
    }
}
 
Example 2
Source File: ZKLogSegmentMetadataStore.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void processResult(int rc, String path, Object ctx, List<String> children, Stat stat) {
    Promise<List<String>> result = ((Promise<List<String>>) ctx);
    if (KeeperException.Code.OK.intValue() == rc) {
        result.setValue(children);
    } else {
        result.setException(KeeperException.create(KeeperException.Code.get(rc)));
    }
}
 
Example 3
Source File: ZKSessionLock.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
private void deleteLockNode(final Promise<BoxedUnit> promise) {
    if (null == currentNode) {
        promise.setValue(BoxedUnit.UNIT);
        return;
    }

    zk.delete(currentNode, -1, new AsyncCallback.VoidCallback() {
        @Override
        public void processResult(final int rc, final String path, Object ctx) {
            lockStateExecutor.submit(lockPath, new SafeRunnable() {
                @Override
                public void safeRun() {
                    if (KeeperException.Code.OK.intValue() == rc) {
                        LOG.info("Deleted lock node {} for {} successfully.", path, lockId);
                    } else if (KeeperException.Code.NONODE.intValue() == rc ||
                            KeeperException.Code.SESSIONEXPIRED.intValue() == rc) {
                        LOG.info("Delete node failed. Node already gone for node {} id {}, rc = {}",
                                new Object[] { path, lockId, KeeperException.Code.get(rc) });
                    } else {
                        LOG.error("Failed on deleting lock node {} for {} : {}",
                                new Object[] { path, lockId, KeeperException.Code.get(rc) });
                    }

                    FailpointUtils.checkFailPointNoThrow(FailpointUtils.FailPointName.FP_LockUnlockCleanup);
                    promise.setValue(BoxedUnit.UNIT);
                }
            });
        }
    }, null);
}
 
Example 4
Source File: Utils.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
private static void handleKeeperExceptionCode(int rc, String pathOrMessage, Promise<BoxedUnit> result) {
    if (KeeperException.Code.OK.intValue() == rc) {
        result.setValue(BoxedUnit.UNIT);
    } else if (DistributedLogConstants.ZK_CONNECTION_EXCEPTION_RESULT_CODE == rc) {
        result.setException(new ZooKeeperClient.ZooKeeperConnectionException(pathOrMessage));
    } else if (DistributedLogConstants.DL_INTERRUPTED_EXCEPTION_RESULT_CODE == rc) {
        result.setException(new DLInterruptedException(pathOrMessage));
    } else {
        result.setException(KeeperException.create(KeeperException.Code.get(rc), pathOrMessage));
    }
}
 
Example 5
Source File: TwitterFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public Void ensurePromiseN() throws Exception {
  Promise<Void> p = new Promise<>();
  Future<Void> f = p;
  for (int i = 0; i < N.n; i++)
    f = f.ensure(ensureF);
  p.setValue(null);
  return Await.result(f);
}
 
Example 6
Source File: TwitterFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public Void ensurePromise() throws Exception {
  Promise<Void> p = new Promise<Void>();
  Future<Void> f = p.ensure(ensureF);
  p.setValue(null);
  return Await.result(f);
}
 
Example 7
Source File: TwitterFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String flatMapPromiseN() throws Exception {
  Promise<String> p = new Promise<String>();
  Future<String> f = p;
  for (int i = 0; i < N.n; i++)
    f = f.flatMap(flatMapF);
  p.setValue(string);
  return Await.result(f);
}
 
Example 8
Source File: LedgerHandleCache.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
/**
 * Close the ledger asynchronously.
 *
 * @param ledgerDesc
 *          ledger descriptor.
 * @return future presenting the closing result.
 */
public Future<Void> asyncCloseLedger(LedgerDescriptor ledgerDesc) {
    final Promise<Void> promise = new Promise<Void>();

    RefCountedLedgerHandle refhandle = getLedgerHandle(ledgerDesc);
    if ((null != refhandle) && (refhandle.removeRef())) {
        refhandle = handlesMap.remove(ledgerDesc);
        if (refhandle.getRefCount() > 0) {
            // In the rare race condition that a ref count was added immediately
            // after the close de-refed it and the remove was called

            // Try to put the handle back in the map
            handlesMap.putIfAbsent(ledgerDesc, refhandle);

            // ReadOnlyLedgerHandles don't have much overhead, so lets just leave
            // the handle open even if it had already been replaced
            promise.setValue(null);
        } else {
            refhandle.handle.asyncClose(new AsyncCallback.CloseCallback() {
                @Override
                public void closeComplete(int rc, LedgerHandle ledgerHandle, Object ctx) {
                    if (BKException.Code.OK == rc) {
                        promise.setValue(null);
                    } else {
                        promise.setException(BKException.create(rc));
                    }
                }
            }, null);
        }
    } else {
        promise.setValue(null);
    }
    return promise;
}
 
Example 9
Source File: TwitterFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String mapPromise() throws Exception {
  Promise<String> p = new Promise<String>();
  Future<String> f = p.map(mapF);
  p.setValue(string);
  return Await.result(f);
}
 
Example 10
Source File: TwitterFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String mapPromise() throws Exception {
  Promise<String> p = new Promise<String>();
  Future<String> f = p.map(mapF);
  p.setValue(string);
  return Await.result(f);
}
 
Example 11
Source File: EnvelopedRecordSetWriter.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
private synchronized void satisfyPromises(long lssn, long entryId, long startSlotId) {
    long nextSlotId = startSlotId;
    for (Promise<DLSN> promise : promiseList) {
        promise.setValue(new DLSN(lssn, entryId, nextSlotId));
        nextSlotId++;
    }
    promiseList.clear();
}
 
Example 12
Source File: TwitterFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String setValueN() throws Exception {
  Promise<String> p = new Promise<String>();
  Future<String> f = p;
  for (int i = 0; i < N.n; i++)
    f = f.map(mapF);
  p.setValue(string);
  return Await.result(f);
}
 
Example 13
Source File: TwitterFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public Void ensurePromiseN() throws Exception {
  Promise<Void> p = new Promise<>();
  Future<Void> f = p;
  for (int i = 0; i < N.n; i++)
    f = f.ensure(ensureF);
  p.setValue(null);
  return Await.result(f);
}
 
Example 14
Source File: TwitterFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String flatMapPromiseN() throws Exception {
  Promise<String> p = new Promise<String>();
  Future<String> f = p;
  for (int i = 0; i < N.n; i++)
    f = f.flatMap(flatMapF);
  p.setValue(string);
  return Await.result(f);
}
 
Example 15
Source File: TwitterFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String flatMapPromise() throws Exception {
  Promise<String> p = new Promise<String>();
  Future<String> f = p.flatMap(flatMapF);
  p.setValue(string);
  return Await.result(f);
}
 
Example 16
Source File: TwitterFutureBenchmark.java    From future with Apache License 2.0 5 votes vote down vote up
@Benchmark
public String mapPromiseN() throws Exception {
  Promise<String> p = new Promise<String>();
  Future<String> f = p;
  for (int i = 0; i < N.n; i++)
    f = f.map(mapF);
  p.setValue(string);
  return Await.result(f);
}
 
Example 17
Source File: TwitterFutureBenchmark.java    From future with Apache License 2.0 4 votes vote down vote up
@Benchmark
public String setValue() throws Exception {
  Promise<String> p = new Promise<String>();
  p.setValue(string);
  return Await.result(p);
}
 
Example 18
Source File: ReadUtils.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
/**
 * Process the search results
 */
static void processSearchResults(
        final String logName,
        final LedgerDescriptor ld,
        final LogSegmentMetadata segment,
        final long transactionId,
        final ExecutorService executorService,
        final LedgerHandleCache handleCache,
        final List<LogRecordWithDLSN> searchResults,
        final int nWays,
        final Optional<LogRecordWithDLSN> prevFoundRecord,
        final Promise<Optional<LogRecordWithDLSN>> promise) {
    int found = -1;
    for (int i = 0; i < searchResults.size(); i++) {
        LogRecordWithDLSN record = searchResults.get(i);
        if (record.getTransactionId() >= transactionId) {
            found = i;
            break;
        }
    }
    if (found == -1) { // all log records' transaction id is less than provided transaction id
        promise.setValue(prevFoundRecord);
        return;
    }
    // we found a log record
    LogRecordWithDLSN foundRecord = searchResults.get(found);

    // we found it
    //   - it is not the first record
    //   - it is the first record in first search entry
    //   - its entry is adjacent to previous search entry
    if (foundRecord.getDlsn().getSlotId() != 0L
            || found == 0
            || foundRecord.getDlsn().getEntryId() == (searchResults.get(found - 1).getDlsn().getEntryId() + 1)) {
        promise.setValue(Optional.of(foundRecord));
        return;
    }

    // otherwise, we need to search
    List<Long> nextSearchBatch = getEntriesToSearch(
            transactionId,
            searchResults.get(found - 1),
            searchResults.get(found),
            nWays);
    if (nextSearchBatch.isEmpty()) {
        promise.setValue(prevFoundRecord);
        return;
    }
    getLogRecordNotLessThanTxIdFromEntries(
            logName,
            ld,
            segment,
            transactionId,
            executorService,
            handleCache,
            nextSearchBatch,
            nWays,
            Optional.of(foundRecord),
            promise);
}
 
Example 19
Source File: TwitterFutureBenchmark.java    From future with Apache License 2.0 4 votes vote down vote up
@Benchmark
public String setValue() throws Exception {
  Promise<String> p = new Promise<String>();
  p.setValue(string);
  return Await.result(p);
}
 
Example 20
Source File: ZKSessionLock.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
/**
 * NOTE: unlockInternal should only after try lock.
 */
private void unlockInternal(final Promise<BoxedUnit> promise) {

    // already closed or expired, nothing to cleanup
    this.epoch.incrementAndGet();
    if (null != watcher) {
        this.zkClient.unregister(watcher);
    }

    if (lockState.inState(State.CLOSED)) {
        promise.setValue(BoxedUnit.UNIT);
        return;
    }

    LOG.info("Lock {} for {} is closed from state {}.",
            new Object[] { lockId, lockPath, lockState.getState() });

    final boolean skipCleanup = lockState.inState(State.INIT) || lockState.inState(State.EXPIRED);

    lockState.transition(State.CLOSING);

    if (skipCleanup) {
        // Nothing to cleanup if INIT (never tried) or EXPIRED (ephemeral node
        // auto-removed)
        lockState.transition(State.CLOSED);
        promise.setValue(BoxedUnit.UNIT);
        return;
    }

    // In any other state, we should clean up the member node
    Promise<BoxedUnit> deletePromise = new Promise<BoxedUnit>();
    deleteLockNode(deletePromise);

    // Set the state to closed after we've cleaned up
    deletePromise.addEventListener(new FutureEventListener<BoxedUnit>() {
        @Override
        public void onSuccess(BoxedUnit complete) {
            lockStateExecutor.submit(lockPath, new SafeRunnable() {
                @Override
                public void safeRun() {
                    lockState.transition(State.CLOSED);
                    promise.setValue(BoxedUnit.UNIT);
                }
            });
        }
        @Override
        public void onFailure(Throwable cause) {
            // Delete failure is quite serious (causes lock leak) and should be
            // handled better
            LOG.error("lock node delete failed {} {}", lockId, lockPath);
            promise.setValue(BoxedUnit.UNIT);
        }
    });
}