本文整理汇总了Java中com.twitter.util.Future类的典型用法代码示例。如果您正苦于以下问题:Java Future类的具体用法?Java Future怎么用?Java Future使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Future类属于com.twitter.util包,在下文中一共展示了Future类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: writeOperation
import com.twitter.util.Future; //导入依赖的package包/类
/**
*
* @param operation
* @return
* @throws IOException
*/
public Tuple<Future<DLSN>, Tuple<BytesReference, Long>> writeOperation(Translog.Operation operation, AtomicLong txid) throws IOException {
BytesStreamOutput out = new BytesStreamOutput();
try (ReleasableLock lock = writeLock.acquire()) {
Future<DLSN> writeResult = null;
out.writeByte(operation.opType().id());
operation.writeTo(out);
BytesReference bytes = out.bytes();
LogRecord logRecord = new LogRecord(txid.incrementAndGet(), bytes.toBytes());
writeResult = logWriter.write(logRecord);
sizeInBytes += (20 + logRecord.getPayload().length);
++ numOperations;
return new Tuple<Future<DLSN>, Tuple<BytesReference, Long>>(writeResult, new Tuple<BytesReference, Long>(bytes, txid.get()));
} catch (TransactionIdOutOfOrderException e) {
throw e;
} finally {
out.close();
}
}
示例2: testReaderLockSharedDlmDoesNotConflict
import com.twitter.util.Future; //导入依赖的package包/类
@Test(timeout = 60000)
public void testReaderLockSharedDlmDoesNotConflict() throws Exception {
String name = runtime.getMethodName();
DistributedLogManager dlm0 = createNewDLM(conf, name);
BKAsyncLogWriter writer = (BKAsyncLogWriter)(dlm0.startAsyncLogSegmentNonPartitioned());
writer.write(DLMTestUtil.getLogRecordInstance(1L));
writer.write(DLMTestUtil.getLogRecordInstance(2L));
writer.closeAndComplete();
DistributedLogManager dlm1 = createNewDLM(conf, name);
Future<AsyncLogReader> futureReader1 = dlm1.getAsyncLogReaderWithLock(DLSN.InitialDLSN);
Future<AsyncLogReader> futureReader2 = dlm1.getAsyncLogReaderWithLock(DLSN.InitialDLSN);
// Both use the same client id, so there's no lock conflict. Not necessarily ideal, but how the
// system currently works.
Await.result(futureReader1);
Await.result(futureReader2);
dlm0.close();
dlm1.close();
}
示例3: zkAsyncCreateFullPathOptimistic
import com.twitter.util.Future; //导入依赖的package包/类
/**
* Asynchronously create zookeeper path recursively and optimistically
*
* @param zkc Zookeeper client
* @param pathToCreate Zookeeper full path
* @param parentPathShouldNotCreate zookeeper parent path should not be created
* @param data Zookeeper data
* @param acl Acl of the zk path
* @param createMode Create mode of zk path
*/
public static Future<BoxedUnit> zkAsyncCreateFullPathOptimistic(
final ZooKeeperClient zkc,
final String pathToCreate,
final Optional<String> parentPathShouldNotCreate,
final byte[] data,
final List<ACL> acl,
final CreateMode createMode) {
final Promise<BoxedUnit> result = new Promise<BoxedUnit>();
zkAsyncCreateFullPathOptimisticRecursive(zkc, pathToCreate, parentPathShouldNotCreate,
data, acl, createMode, new AsyncCallback.StringCallback() {
@Override
public void processResult(int rc, String path, Object ctx, String name) {
handleKeeperExceptionCode(rc, path, result);
}
}, result);
return result;
}
示例4: schedule
import com.twitter.util.Future; //导入依赖的package包/类
/**
* Dont schedule if we're closed - closeLock is acquired to close, so if we acquire the
* lock and discover we're not closed, we won't schedule.
*/
private java.util.concurrent.Future<?> schedule(Runnable runnable, long delayMs) {
closeLock.readLock().lock();
try {
if (closed) {
return null;
} else if (delayMs > 0) {
return executorService.schedule(runnable, delayMs, TimeUnit.MILLISECONDS);
} else {
return executorService.submit(runnable);
}
} catch (RejectedExecutionException ree) {
logger.error("Failed to schedule task {} in {} ms : ",
new Object[] { runnable, delayMs, ree });
return null;
} finally {
closeLock.readLock().unlock();
}
}
示例5: multiPut
import com.twitter.util.Future; //导入依赖的package包/类
@Override
public void multiPut(List<List<Object>> keys, List<T> vals) {
try {
List<Future> futures = new ArrayList(keys.size());
for(int i=0; i<keys.size(); i++) {
String key = toSingleKey(keys.get(i));
T val = vals.get(i);
byte[] serialized = _ser.serialize(val);
final ChannelBuffer entry = ChannelBuffers.wrappedBuffer(serialized);
Time expiry =
Time.fromMilliseconds(_opts.expiration);
futures.add(_client.set(key, 0 /* no flags */, expiry, entry));
}
for(Future future: futures) {
future.get();
}
// _mwrites.incrBy(futures.size());
} catch(Exception e) {
checkMemcachedException(e);
}
}
示例6: doDeleteAndRemoveAsync
import com.twitter.util.Future; //导入依赖的package包/类
private Future<Void> doDeleteAndRemoveAsync(final String streamName) {
Stream stream = streams.get(streamName);
if (null == stream) {
logger.warn("No stream {} to delete.", streamName);
return Future.exception(new UnexpectedException("No stream " + streamName + " to delete."));
} else {
Future<Void> result;
logger.info("Deleting stream {}, {}", streamName, stream);
try {
stream.delete();
result = stream.requestClose("Stream Deleted");
} catch (IOException e) {
logger.error("Failed on removing stream {} : ", streamName, e);
result = Future.exception(e);
}
return result;
}
}
示例7: handleServiceTimeout
import com.twitter.util.Future; //导入依赖的package包/类
/**
* Close the stream and schedule cache eviction at some point in the future.
* We delay this as a way to place the stream in a probationary state--cached
* in the proxy but unusable.
* This mechanism helps the cluster adapt to situations where a proxy has
* persistent connectivity/availability issues, because it keeps an affected
* stream off the proxy for a period of time, hopefully long enough for the
* issues to be resolved, or for whoop to kick in and kill the shard.
*/
synchronized void handleServiceTimeout(String reason) {
if (StreamStatus.isUnavailable(status)) {
return;
}
// Mark stream in error state
setStreamInErrorStatus();
// Async close request, and schedule eviction when its done.
Future<Void> closeFuture = requestClose(reason, false /* dont remove */);
closeFuture.onSuccess(new AbstractFunction1<Void, BoxedUnit>() {
@Override
public BoxedUnit apply(Void result) {
streamManager.scheduleRemoval(StreamImpl.this, streamProbationTimeoutMs);
return BoxedUnit.UNIT;
}
});
}
示例8: tryObtain
import com.twitter.util.Future; //导入依赖的package包/类
@Override
public synchronized Future<LedgerHandle> tryObtain(final Transaction<Object> txn,
final OpListener<LedgerHandle> listener) {
if (Phase.ERROR == phase) {
return Future.exception(new AllocationException(Phase.ERROR,
"Error on allocating ledger under " + allocatePath));
}
if (Phase.HANDING_OVER == phase || Phase.HANDED_OVER == phase || null != tryObtainTxn) {
return Future.exception(new ConcurrentObtainException(phase,
"Ledger handle is handling over to another thread : " + phase));
}
tryObtainTxn = txn;
tryObtainListener = listener;
if (null != allocatedLh) {
completeAllocation(allocatedLh);
}
return allocatePromise;
}
示例9: apply
import com.twitter.util.Future; //导入依赖的package包/类
@Override
public Future<Rep> apply(Req req, Service<Req, Rep> service) {
Future<Rep> result = null;
outstandingAsync.inc();
final Stopwatch stopwatch = Stopwatch.createStarted();
try {
result = service.apply(req);
serviceExec.registerSuccessfulEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
} finally {
outstandingAsync.dec();
if (null == result) {
serviceExec.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS));
}
}
return result;
}
示例10: asyncReadFirstUserRecord
import com.twitter.util.Future; //导入依赖的package包/类
private Future<LogRecordWithDLSN> asyncReadFirstUserRecord(LogSegmentMetadata ledger, DLSN beginDLSN) {
final LedgerHandleCache handleCache =
LedgerHandleCache.newBuilder().bkc(bookKeeperClient).conf(conf).build();
return ReadUtils.asyncReadFirstUserRecord(
getFullyQualifiedName(),
ledger,
firstNumEntriesPerReadLastRecordScan,
maxNumEntriesPerReadLastRecordScan,
new AtomicInteger(0),
scheduler,
handleCache,
beginDLSN
).ensure(new AbstractFunction0<BoxedUnit>() {
@Override
public BoxedUnit apply() {
handleCache.clear();
return BoxedUnit.UNIT;
}
});
}
示例11: testGetLogRecordCountWithCompletedAndInprogressLedgers
import com.twitter.util.Future; //导入依赖的package包/类
@Test(timeout = 60000)
public void testGetLogRecordCountWithCompletedAndInprogressLedgers() throws Exception {
String streamName = runtime.getMethodName();
BKDistributedLogManager bkdlm = (BKDistributedLogManager) createNewDLM(conf, streamName);
long txid = 1;
txid += DLMTestUtil.generateLogSegmentNonPartitioned(bkdlm, 0, 5, txid);
AsyncLogWriter out = bkdlm.startAsyncLogSegmentNonPartitioned();
Await.result(out.write(DLMTestUtil.getLargeLogRecordInstance(txid++, false)));
Await.result(out.write(DLMTestUtil.getLargeLogRecordInstance(txid++, false)));
Await.result(out.write(DLMTestUtil.getLargeLogRecordInstance(txid++, false)));
BKLogReadHandler readHandler = bkdlm.createReadHandler();
List<LogSegmentMetadata> ledgerList = readHandler.getLedgerList(false, false, LogSegmentMetadata.COMPARATOR, false);
assertEquals(2, ledgerList.size());
assertFalse(ledgerList.get(0).isInProgress());
assertTrue(ledgerList.get(1).isInProgress());
Future<Long> count = null;
count = readHandler.asyncGetLogRecordCount(new DLSN(1, 0, 0));
assertEquals(7, Await.result(count).longValue());
Utils.close(out);
}
示例12: asyncGetLogRecordCount
import com.twitter.util.Future; //导入依赖的package包/类
/**
* Get a count of records between beginDLSN and the end of the stream.
*
* @param beginDLSN dlsn marking the start of the range
* @return the count of records present in the range
*/
public Future<Long> asyncGetLogRecordCount(final DLSN beginDLSN) {
return checkLogStreamExistsAsync().flatMap(new Function<Void, Future<Long>>() {
public Future<Long> apply(Void done) {
return asyncGetFullLedgerList(true, false).flatMap(new Function<List<LogSegmentMetadata>, Future<Long>>() {
public Future<Long> apply(List<LogSegmentMetadata> ledgerList) {
List<Future<Long>> futureCounts = new ArrayList<Future<Long>>(ledgerList.size());
for (LogSegmentMetadata ledger : ledgerList) {
if (ledger.getLogSegmentSequenceNumber() >= beginDLSN.getLogSegmentSequenceNo()) {
futureCounts.add(asyncGetLogRecordCount(ledger, beginDLSN));
}
}
return Future.collect(futureCounts).map(new Function<List<Long>, Long>() {
public Long apply(List<Long> counts) {
return sum(counts);
}
});
}
});
}
});
}
示例13: asyncReadEntries
import com.twitter.util.Future; //导入依赖的package包/类
/**
* Async Read Entries
*
* @param ledgerDesc
* ledger descriptor
* @param first
* first entry
* @param last
* second entry
*/
public Future<Enumeration<LedgerEntry>> asyncReadEntries(
LedgerDescriptor ledgerDesc, long first, long last) {
RefCountedLedgerHandle refHandle = handlesMap.get(ledgerDesc);
if (null == refHandle) {
LOG.error("Accessing ledger {} without opening.", ledgerDesc);
return Future.exception(BKException.create(BKException.Code.UnexpectedConditionException));
}
final Promise<Enumeration<LedgerEntry>> promise = new Promise<Enumeration<LedgerEntry>>();
refHandle.handle.asyncReadEntries(first, last, new AsyncCallback.ReadCallback() {
@Override
public void readComplete(int rc, LedgerHandle lh, Enumeration<LedgerEntry> entries, Object ctx) {
if (BKException.Code.OK == rc) {
promise.setValue(entries);
} else {
promise.setException(BKException.create(rc));
}
}
}, null);
return promise;
}
示例14: asyncClose
import com.twitter.util.Future; //导入依赖的package包/类
/**
* Close the metadata accessor, freeing any resources it may hold.
* @return future represents the close result.
*/
@Override
public Future<Void> asyncClose() {
Promise<Void> closeFuture;
synchronized (this) {
if (null != closePromise) {
return closePromise;
}
closeFuture = closePromise = new Promise<Void>();
}
// NOTE: ownWriterZKC and ownReaderZKC are mostly used by tests
// the managers created by the namespace - whose zkc will be closed by namespace
try {
if (ownWriterZKC) {
writerZKC.close();
}
if (ownReaderZKC) {
readerZKC.close();
}
} catch (Exception e) {
LOG.warn("Exception while closing distributed log manager", e);
}
FutureUtils.setValue(closeFuture, null);
return closeFuture;
}
示例15: asyncClose
import com.twitter.util.Future; //导入依赖的package包/类
public Future<Void> asyncClose() {
DistributedLock lockToClose;
synchronized (this) {
if (null != lockAcquireFuture && !lockAcquireFuture.isDefined()) {
FutureUtils.cancel(lockAcquireFuture);
}
lockToClose = readLock;
}
return Utils.closeSequence(scheduler, readAheadWorker, lockToClose)
.flatMap(new AbstractFunction1<Void, Future<Void>>() {
@Override
public Future<Void> apply(Void result) {
if (null != readAheadCache) {
readAheadCache.clear();
}
if (null != handleCache) {
handleCache.clear();
}
return BKLogReadHandler.super.asyncClose();
}
});
}