本文整理匯總了Java中io.atomix.utils.concurrent.Futures類的典型用法代碼示例。如果您正苦於以下問題:Java Futures類的具體用法?Java Futures怎麽用?Java Futures使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
Futures類屬於io.atomix.utils.concurrent包,在下文中一共展示了Futures類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: openProxy
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
/**
* Opens a new client.
*
* @return a future to be completed once the client has been opened
*/
private CompletableFuture<PrimitiveProxy> openProxy() {
if (connected) {
log.debug("Opening proxy session");
clientFuture = new OrderedFuture<>();
openProxy(clientFuture);
return clientFuture.thenApply(client -> {
synchronized (this) {
this.log = ContextualLoggerFactory.getLogger(getClass(), LoggerContext.builder(PrimitiveProxy.class)
.addValue(client.sessionId())
.add("type", client.serviceType())
.add("name", client.name())
.build());
this.proxy = client;
client.addStateChangeListener(this::onStateChange);
eventListeners.forEach(client::addEventListener);
onStateChange(PrimitiveProxy.State.CONNECTED);
}
return client;
});
}
return Futures.exceptionalFuture(new IllegalStateException("Client not open"));
}
示例2: applyCommand
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
/**
* Applies a command entry to the state machine.
* <p>
* Command entries result in commands being executed on the user provided {@link PrimitiveService} and a
* response being sent back to the client by completing the returned future. All command responses are
* cached in the command's {@link RaftSession} for fault tolerance. In the event that the same command
* is applied to the state machine more than once, the original response will be returned.
* <p>
* Command entries are written with a sequence number. The sequence number is used to ensure that
* commands are applied to the state machine in sequential order. If a command entry has a sequence
* number that is less than the next sequence number for the session, that indicates that it is a
* duplicate of a command that was already applied. Otherwise, commands are assumed to have been
* received in sequential order. The reason for this assumption is because leaders always sequence
* commands as they're written to the log, so no sequence number will be skipped.
*/
private CompletableFuture<OperationResult> applyCommand(Indexed<CommandEntry> entry) {
// First check to ensure that the session exists.
RaftSession session = raft.getSessions().getSession(entry.entry().session());
// If the session is null, return an UnknownSessionException. Commands applied to the state machine must
// have a session. We ensure that session register/unregister entries are not compacted from the log
// until all associated commands have been cleaned.
if (session == null) {
logger.warn("Unknown session: " + entry.entry().session());
return Futures.exceptionalFuture(new RaftException.UnknownSession("unknown session: " + entry.entry().session()));
}
// Increment the load counter to avoid snapshotting under high load.
raft.getLoadMonitor().recordEvent();
// Execute the command using the state machine associated with the session.
return session.getService()
.executeCommand(
entry.index(),
entry.entry().sequenceNumber(),
entry.entry().timestamp(),
session,
entry.entry().operation());
}
示例3: applyQuery
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
/**
* Applies a query entry to the state machine.
* <p>
* Query entries are applied to the user {@link PrimitiveService} for read-only operations.
* Because queries are read-only, they may only be applied on a single server in the cluster,
* and query entries do not go through the Raft log. Thus, it is critical that measures be taken
* to ensure clients see a consistent view of the cluster event when switching servers. To do so,
* clients provide a sequence and version number for each query. The sequence number is the order
* in which the query was sent by the client. Sequence numbers are shared across both commands and
* queries. The version number indicates the last index for which the client saw a command or query
* response. In the event that the lastApplied index of this state machine does not meet the provided
* version number, we wait for the state machine to catch up before applying the query. This ensures
* clients see state progress monotonically even when switching servers.
* <p>
* Because queries may only be applied on a single server in the cluster they cannot result in the
* publishing of session events. Events require commands to be written to the Raft log to ensure
* fault-tolerance and consistency across the cluster.
*/
private CompletableFuture<OperationResult> applyQuery(Indexed<QueryEntry> entry) {
RaftSession session = raft.getSessions().getSession(entry.entry().session());
// If the session is null then that indicates that the session already timed out or it never existed.
// Return with an UnknownSessionException.
if (session == null) {
logger.warn("Unknown session: " + entry.entry().session());
return Futures.exceptionalFuture(new RaftException.UnknownSession("unknown session " + entry.entry().session()));
}
// Execute the query using the state machine associated with the session.
return session.getService()
.executeQuery(
entry.index(),
entry.entry().sequenceNumber(),
entry.entry().timestamp(),
session,
entry.entry().operation());
}
示例4: shutdown
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
/**
* Shuts down the server without leaving the Raft cluster.
*
* @return A completable future to be completed once the server has been shutdown.
*/
public CompletableFuture<Void> shutdown() {
if (!started) {
return Futures.exceptionalFuture(new IllegalStateException("context not open"));
}
CompletableFuture<Void> future = new CompletableFuture<>();
context.getThreadContext().execute(() -> {
started = false;
context.transition(Role.INACTIVE);
future.complete(null);
});
return future.whenCompleteAsync((result, error) -> {
context.close();
started = false;
});
}
示例5: forward
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
/**
* Forwards the given request to the leader if possible.
*/
protected <T extends RaftRequest, U extends RaftResponse> CompletableFuture<U> forward(T request, BiFunction<NodeId, T, CompletableFuture<U>> function) {
CompletableFuture<U> future = new CompletableFuture<>();
DefaultRaftMember leader = raft.getLeader();
if (leader == null) {
return Futures.exceptionalFuture(new RaftException.NoLeader("No leader found"));
}
function.apply(leader.nodeId(), request).whenCompleteAsync((response, error) -> {
if (error == null) {
future.complete(response);
} else {
future.completeExceptionally(error);
}
}, raft.getThreadContext());
return future;
}
示例6: set
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
@Override
public CompletableFuture<Versioned<byte[]>> set(DocumentPath path, byte[] value) {
return proxy.<Update, DocumentTreeResult<Versioned<byte[]>>>invoke(UPDATE,
SERIALIZER::encode,
new Update(checkNotNull(path), Optional.ofNullable(value), Match.any(), Match.any()),
SERIALIZER::decode)
.thenCompose(result -> {
if (result.status() == INVALID_PATH) {
return Futures.exceptionalFuture(new NoSuchDocumentPathException());
} else if (result.status() == ILLEGAL_MODIFICATION) {
return Futures.exceptionalFuture(new IllegalDocumentModificationException());
} else {
return CompletableFuture.completedFuture(result);
}
}).thenApply(result -> result.result());
}
示例7: buildAsync
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<LeaderElector<T>> buildAsync() {
PrimitiveProtocol protocol = protocol();
PartitionGroup partitions = managementService.getPartitionService().getPartitionGroup(protocol);
Map<PartitionId, CompletableFuture<AsyncLeaderElector<T>>> electors = Maps.newConcurrentMap();
for (Partition partition : partitions.getPartitions()) {
electors.put(partition.id(),
newLeaderElector(partition.getPrimitiveClient().newProxy(name(), primitiveType(), protocol)));
}
Partitioner<String> partitioner = topic -> partitions.getPartition(topic).id();
return Futures.allOf(new ArrayList<>(electors.values()))
.thenApply(e -> new PartitionedAsyncLeaderElector<T>(name(), Maps.transformValues(electors, v -> v.getNow(null)), partitioner).sync());
}
示例8: unicast
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
@Override
public <M> CompletableFuture<Void> unicast(
String subject,
M message,
Function<M, byte[]> encoder,
NodeId toNodeId) {
try {
byte[] payload = new ClusterMessage(
localNodeId,
subject,
encoder.apply(message)
).getBytes();
return doUnicast(subject, payload, toNodeId);
} catch (Exception e) {
return Futures.exceptionalFuture(e);
}
}
示例9: getChildren
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
@Override
public CompletableFuture<Map<String, Versioned<byte[]>>> getChildren(DocumentPath path) {
return proxy.<GetChildren, DocumentTreeResult<Map<String, Versioned<byte[]>>>>invoke(
GET_CHILDREN,
SERIALIZER::encode,
new GetChildren(checkNotNull(path)),
SERIALIZER::decode)
.thenCompose(result -> {
if (result.status() == INVALID_PATH) {
return Futures.exceptionalFuture(new NoSuchDocumentPathException());
} else if (result.status() == ILLEGAL_MODIFICATION) {
return Futures.exceptionalFuture(new IllegalDocumentModificationException());
} else {
return CompletableFuture.completedFuture(result);
}
}).thenApply(result -> result.result());
}
示例10: prepare
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
@Override
public CompletableFuture<Boolean> prepare(TransactionLog<MapUpdate<K, V>> transactionLog) {
Map<AsyncConsistentMap<K, V>, List<MapUpdate<K, V>>> updatesGroupedByMap = Maps.newIdentityHashMap();
transactionLog.records().forEach(update -> {
AsyncConsistentMap<K, V> map = getMap(update.key());
updatesGroupedByMap.computeIfAbsent(map, k -> Lists.newLinkedList()).add(update);
});
Map<AsyncConsistentMap<K, V>, TransactionLog<MapUpdate<K, V>>> transactionsByMap =
Maps.transformValues(updatesGroupedByMap,
list -> new TransactionLog<>(transactionLog.transactionId(), transactionLog.version(), list));
return Futures.allOf(transactionsByMap.entrySet()
.stream()
.map(e -> e.getKey().prepare(e.getValue()))
.collect(Collectors.toList()))
.thenApply(list -> list.stream().reduce(Boolean::logicalAnd).orElse(true));
}
示例11: removeNode
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
@Override
public CompletableFuture<Versioned<byte[]>> removeNode(DocumentPath path) {
if (path.equals(DocumentPath.from("root"))) {
return Futures.exceptionalFuture(new IllegalDocumentModificationException());
}
return proxy.<Update, DocumentTreeResult<Versioned<byte[]>>>invoke(UPDATE,
SERIALIZER::encode,
new Update(checkNotNull(path), null, Match.any(), Match.ifNotNull()),
SERIALIZER::decode)
.thenCompose(result -> {
if (result.status() == INVALID_PATH) {
return Futures.exceptionalFuture(new NoSuchDocumentPathException());
} else if (result.status() == ILLEGAL_MODIFICATION) {
return Futures.exceptionalFuture(new IllegalDocumentModificationException());
} else {
return CompletableFuture.completedFuture(result);
}
}).thenApply(result -> result.result());
}
示例12: removeAllMatching
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
@Override
public void removeAllMatching(Predicate<V> p, Handler<AsyncResult<Void>> handler) {
map.entries().thenCompose(entries -> Futures.allOf(entries.stream()
.filter(e -> p.test(e.getValue()))
.map(e -> map.remove(e.getKey(), e.getValue()))
.collect(Collectors.toList())))
.whenComplete(VertxFutures.voidHandler(handler, vertx.getOrCreateContext()));
}
示例13: execute
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
@Override
public CompletableFuture<byte[]> execute(PrimitiveOperation operation) {
if (getState() == PrimitiveProxy.State.CLOSED) {
return Futures.exceptionalFuture(new PrimitiveException.Unavailable());
}
CompletableFuture<byte[]> future = new CompletableFuture<>();
execute(operation, 1, future);
return future;
}
示例14: execute
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
@Override
public CompletableFuture<ExecuteResponse> execute(ExecuteRequest request) {
logRequest(request);
if (request.operation().id().type() == OperationType.COMMAND) {
return executeCommand(request).thenApply(this::logResponse);
} else if (request.operation().id().type() == OperationType.QUERY) {
return executeQuery(request).thenApply(this::logResponse);
}
return Futures.exceptionalFuture(new IllegalArgumentException("Unknown operation type"));
}
示例15: getServer
import io.atomix.utils.concurrent.Futures; //導入依賴的package包/類
private CompletableFuture<TestPrimaryBackupServerProtocol> getServer(NodeId memberId) {
TestPrimaryBackupServerProtocol server = server(memberId);
if (server != null) {
return Futures.completedFuture(server);
} else {
return Futures.exceptionalFuture(new ConnectException());
}
}